#
# set -o errexit -o noglob are assumed.
#

exp_pkg_env_source() {
	local _pkg_name="${1}" _tgt_name="${2}"				\
		_tgt_name_uc _pkg_name_uc _pkg_name_inherit_uc		\
		_build_type_uc _vname_dst _vars_set="";
	ex_rtl_fileop source_opt "vars/${_pkg_name}.vars";
	_tgt_name_uc="$(ex_rtl_toupper "${_tgt_name}")";
	_pkg_name_uc="$(ex_rtl_toupper "${_pkg_name}")";
	ex_rtl_set_vars BUILD_TYPE					\
		"DEFAULT ${_tgt_name_uc} PKG_${_pkg_name_uc}"		\
		_vars_set;
	_build_type_uc="$(ex_rtl_toupper "${PKG_BUILD_TYPE}")";
	ex_rtl_set_vars INHERIT_FROM "PKG_${_pkg_name_uc}" _vars_set;
	_pkg_name_inherit_uc="$(ex_rtl_toupper "${PKG_INHERIT_FROM}")";
	for _vname_dst in $(ex_rtl_lfilter_not				\
			"${DEFAULT_BUILD_VARS}" BUILD_TYPE); do
		if [ -n "${_pkg_name_inherit_uc}" ]; then
			ex_rtl_set_vars "${_vname_dst}"			\
				"DEFAULT DEFAULT_${_build_type_uc}	\
				${_tgt_name_uc}				\
				PKG_${_pkg_name_inherit_uc}		\
				PKG_${_pkg_name_uc}" _vars_set;
		else
			ex_rtl_set_vars "${_vname_dst}"			\
				"DEFAULT DEFAULT_${_build_type_uc}	\
				${_tgt_name_uc} PKG_${_pkg_name_uc}"	\
				_vars_set;
		fi;
	done;
	ex_rtl_unset_vars $(ex_rtl_lfilter_not				\
		"$(set | awk -F= '/^PKG_/{print $1}' | sort)"		\
		"${_vars_set}");
};

ex_pkg_env() {
	local _pkg_name="${1}" _tgt_name="${2}" _restart_at="${3}" _vname;
	exp_pkg_env_source "${_pkg_name}" "${_tgt_name}";
	: ${PKG_NAME:="${_pkg_name}"};
	: ${MIDIPIX_BUILD_PWD:="$(pwd)"};
	: ${PKG_BASE_DIR:="${BUILD_WORKDIR}/${_pkg_name}-${PKG_BUILD_TYPE}-${PKG_TARGET}"};
	: ${PKG_FNAME:="${PKG_URL##*/}"};
	: ${PKG_BUILD_STEPS:="$(ex_rtl_lfilter_not "${DEFAULT_BUILD_STEPS}"		\
		"${PKG_BUILD_STEPS_DISABLE}")"};
	if [ -z "${PKG_SUBDIR}" ]; then
		if [ -n "${PKG_URLS_GIT}" ]; then
			PKG_SUBDIR="${PKG_URLS_GIT%%=*}";
		else case "${PKG_FNAME}" in
		*.t*)	PKG_SUBDIR="${PKG_FNAME%%.t*}"; ;;
		*)	PKG_SUBDIR="${_pkg_name}"; ;;
		esac; fi;
	fi;
	if [ -z "${PKG_BUILD_DIR}" ]; then
		case "${PKG_IN_TREE:-0}" in
		0) PKG_BUILD_DIR="obj"; ;;
		1) PKG_BUILD_DIR="${PKG_SUBDIR}"; ;;
		esac;
	fi;
	PKG_BUILD_DIR="${PKG_BASE_DIR}/${PKG_BUILD_DIR}";
	PKG_CONFIGURE="${PKG_BASE_DIR}/${PKG_CONFIGURE:-${PKG_SUBDIR}/configure}";
	PKG_DESTDIR="${PKG_BASE_DIR}/${PKG_DESTDIR:-destdir}";
	ex_rtl_push_IFS :; for _vname in ${PKG_ENV_VARS_EXTRA}; do
		export "${_vname}";
	done; ex_rtl_pop_IFS;
};

ex_pkg_state_set() { ex_rtl_state_set "${BUILD_WORKDIR}" "${@}"; };
ex_pkg_state_test() { ex_rtl_state_test "${BUILD_WORKDIR}" "${@}"; };

# vim:filetype=sh