#!/usr/bin/env bash
sysroot="$(dirname "$(dirname "$(dirname "$0")")")"
basedir="$(basename "${sysroot}")"

declare -a prefix
if [ "${basedir}" = "sysroot-cross" ]; then
    sysroot="$(dirname "${sysroot}")/sysroot-target"
    prefix="${sysroot}/usr"
    whitelist="${PKGCONFIG_WHITELIST_TARGET}"
elif [ "${basedir}" = "sysroot-host" ]; then
    prefix="${sysroot}/usr"
    whitelist="${PKGCONFIG_WHITELIST_HOST}"
else
    echo "$(basename ${0}): failed to determine prefix" >&2
    exit 1
fi

declare -a libdirs libpaths incpaths
# try to find all our pkgconfig paths.
libdirs=( $(find ${prefix} -maxdepth 3 -type d -name pkgconfig) )
for libdir in "${libdirs[@]}"; do
    lib="$(basename $(dirname ${libdir}))"
    libpaths+=( "${libdir[@]/%//../../${lib}}" "${libdir[@]/%//../${lib}}" )
    incpaths+=( "${libdir[@]/%//../../include}" "${libdir[@]/%//../include}" )
    libpaths+=( "/usr/${lib}" "/${lib}" )
done
incpaths+=( "/usr/include" "/include" )

orig_IFS="${IFS}"
IFS=":"
# make sure no other sysroot is set
# it conflicts with our own sysroot handling
unset PKG_CONFIG_SYSROOT_DIR
# never allow systemd paths
# they may include /usr/{lib,include} which is never correct
unset PKG_CONFIG_ALLOW_SYSTEM_CFLAGS
unset PKG_CONFIG_ALLOW_SYSTEM_LIBS
# default pkg-config search path
export PKG_CONFIG_LIBDIR="${libdirs[*]}"
# default search path that will be dropped from --libs
export PKG_CONFIG_SYSTEM_LIBRARY_PATH="${libpaths[*]}"
# default search path that will be dropped from --cflags
export PKG_CONFIG_SYSTEM_INCLUDE_PATH="${incpaths[*]}"
IFS="${orig_IFS}"

for ((i = 1; i <= ${#}; i++)); do
    case "${!i}" in
	--variable*)
	    found_var=${!i#"--variable="}
	    break
	    ;;
	*)
	    ;;
    esac
done

#
# this sed will sanitize pkg-config's output. it will remove:
#
# "/usr/lib/pkgconfig/../../.."
# "/lib/pkgconfig/../.."
#
declare -a args
args=( \
    "-e" "s~/usr/lib/pkgconfig/\.\./\.\./\.\.~~g" \
    "-e" "s~/lib/pkgconfig/\.\./\.\.~~g" \
    )

if [ -n "${found_var}" -a \
    "${PTXDIST_PKG_CONFIG_VAR_NO_SYSROOT#*${found_var}}" != "${PTXDIST_PKG_CONFIG_VAR_NO_SYSROOT}" ]; then
    #
    # remove sysroot for variables that return a path
    #
    args[${#args[@]}]="-e"
    args[${#args[@]}]="s~^${sysroot}/~/~"
fi

check_pipe_status() {
	for _pipe_status in "${PIPESTATUS[@]}"; do
		if [ ${_pipe_status} -ne 0 ]; then
			return ${_pipe_status}
		fi
	done
}

print_pkg() {
    args=()
    while [ $# -gt 0 ]; do
	case "${1}" in
	    --variable|--define-variable|--atleast-pkgconfig-version|--*-version)
		shift
		;;
	    --*)
		;;
	    *)
		args[${#args[@]}]="${1}"
		;;
	esac
	shift
    done
    if [ ${#args[*]} -ne 0 ]; then
	pkgconf --print-provides "${args[@]}" 2> "${error}" | awk '{print $1}' &&
	check_pipe_status
    fi
}

if [ -n "${PKGCONFIG_WHITELIST_SRC}" -a "${1}" != "--version" -a "${1}" != "--help" ]; then
    error="$(mktemp "${PTXDIST_TEMPDIR}/pkg-config.XXXXXX")"
    pkgs="$(print_pkg "${@}")"
    if [ $? -ne 0 ]; then
	# meson suppresses any pkg-config output, so dump it into the logfile instead
	if [ "${pkg_conf_tool}" = "meson" -a -n "${PTXDIST_LOGFILE_PATH}" ]; then
	    echo "$(basename ${0}) $*" >>"${PTXDIST_LOGFILE_PATH}"
	    cat "${error}" >>"${PTXDIST_LOGFILE_PATH}"
	else
	    cat "${error}" >&2
	fi
	rm "${error}"
	exit 1
    fi
    rm "${error}"
    for pkg in ${pkgs}; do
	if [[ ! " ${whitelist} " =~ " ${pkg} " && ! "${pkg}" =~ '-uninstalled' ]]; then
	    if [ "${pkg_conf_tool}" = "meson" -a -n "${PTXDIST_LOGFILE_PATH}" ]; then
		echo "$(basename "${0}"): warning: blocking '${pkg}': not selected by '${PKGCONFIG_WHITELIST_SRC}'" >>"${PTXDIST_LOGFILE_PATH}"
	    else
		echo "$(basename "${0}"): warning: blocking '${pkg}': not selected by '${PKGCONFIG_WHITELIST_SRC}'" >&2
	    fi
	    exit 1
	fi
    done
fi
pkgconf "${@}" | sed "${args[@]}"
check_pipe_status
