#! /bin/bash
#
# Cross-version of pkg-config
#

platform=${0%/sysroots/native/*}

# The command may be a link to the real $host_alias-pkg-config
cmd="$(readlink -e $0)"
cross_name="$(basename $cmd -pkg-config)"

# Export the cross-pkg-config environment, for the provided sysroot/bin/<target-triplet>-pkg-config
export_cross_pkg_config_setup() {
	local platform="$1"
	local cross_name="$2"
	local sysroot cross_sysroot platform_sysroot
	local CROSS_COMPILE="${cross_name}-"
	local libc_so=$(${CROSS_COMPILE}gcc --print-file-name=libc.so)

	if [ -n "$libc_so" ]; then
		sysroot=$(dirname $libc_so \
			 | sed -e 's|//|/|g' -e 's|//|/|g' -e 's|//|/|g' -e 's|//|/|g' \
			       -e 's|/[^./][^/]*/\.\./|/|g' -e 's|/[^./][^/]*/\.\./|/|g' \
			       -e 's|/[^./][^/]*/\.\./|/|g' -e 's|/[^./][^/]*/\.\./|/|g' \
			       -e 's|/usr/lib$||' -e 's|/lib$||')
		if [ -d "$sysroot" ]; then
			cross_sysroot="$sysroot"
		fi
	fi
	platform_sysroot=$platform/sysroots/$cross_name

	PKG_CONFIG_LIBDIR=$platform_sysroot/usr/lib/pkgconfig
	PKG_CONFIG_PATH=
	local dir subdir sep=
	for sysroot in $platform_sysroot $cross_sysroot; do
		if [ -z "$sysroot" -o ! -d "$sysroot" ]; then continue; fi
		for subdir in /usr/lib /usr/share /usr/local/lib /usr/local/share; do
			dir="${sysroot}/${subdir}/pkgconfig"
			if [ -d "$dir" ] && [[ ! ":${PKG_CONFIG_PATH}:" =~ ":${dir}:" ]]; then
				PKG_CONFIG_PATH="${PKG_CONFIG_PATH}${sep}${dir}"
				sep=':'
			fi
		done
	done

	PKG_CONFIG_DISABLE_UNINSTALLED=set
	PKG_CONFIG_SYSROOT_DIR="$platform_sysroot"
	PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=set
	PKG_CONFIG_ALLOW_SYSTEM_LIBS=set

	export PKG_CONFIG_LIBDIR
	export PKG_CONFIG_PATH
	export PKG_CONFIG_DISABLE_UNINSTALLED
	export PKG_CONFIG_SYSROOT_DIR
	export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS
	export PKG_CONFIG_ALLOW_SYSTEM_LIBS
}

# Export the cross-pkg-config environment
export_cross_pkg_config_setup $platform $cross_name

# Then call the installed pkg-config -- currently we skipped the native sysroot version
# as it is another version of this script to have the installed pkg-config 
# reference the native sysroot... 
for path in ${PATH//:/ }; do
	if [[ " $path" =~ " $platform/sysroots/native/" ]]; then continue; fi
	if [ -x ${path%/}/pkg-config ]; then
		exec ${path%/}/pkg-config "$@"
	fi
done

echo "pkg-config: File not found" >&2
exit 1
