#!/bin/sh
# Copyright 2008-2025 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

#
# This creates a pkg-config frontend that has the form TARGET-pkg-config
# as this is the utility that autoconf scripts will automatically search
# for when cross-compiling for TARGET.  Here we setup the pkg config env
# paths so that the .pc files that are searched and used come from the
# staging directory rather than the host system.
#

#
# Helper functions.  So very helpful.
#
msg_to_stderr() { echo "cross-pkg-config: $*" 1>&2 ; }
warn() { msg_to_stderr "warning: $*" ; }
error() {
	msg_to_stderr "error: $*"
	exit 1
}

if [ -z "${REAL_PKG_CONFIG}" ]; then
	REAL_PKG_CONFIG="x86_64-pc-linux-gnu-pkg-config"
fi
if ! command -v "${REAL_PKG_CONFIG}" >/dev/null; then
	REAL_PKG_CONFIG=pkg-config
fi

# abort infinite loop due to misconfiguration
[ "${0##*/}" = "${REAL_PKG_CONFIG}" ] && error "aborting infinite loop! (make sure to delete uClinux-dist/tools/pkg-config)"

#
# Allow very basic checks.  This is not very sophisticated, but should get the
# job done, practically speaking.
#

case $1 in
--about|--help|--version)
  exec "${REAL_PKG_CONFIG}" "$@"
  ;;
esac

#
# Sanity/distro checks
#

if [ "$1" = "--cross-pkg-config-install" ] ; then
	# --cross-pkg-config-install <sysroot dir> [pkg-config wrapper]
	pkg_path="$2"
	pkg_config="${3:-$0}"
	sed -i.tmp \
		-e "s:@CROSS_PKG_CONFIG_INSTALLED@:installed:" \
		-e "s:@CROSS_PKG_CONFIG_PATH@:${pkg_path}:" \
		"${pkg_config}"
	rm -f "${pkg_config}".tmp
	chmod a+rx "${pkg_config}"
	exit 0
fi

export PKG_CONFIG_LIBDIR=
unset PREFIX

if [ -z "${CHOST}" ] ; then
	CHOST=${0##*/}
	CHOST=${CHOST%-pkg-config}
fi

if [ -n "${ESYSROOT+x}" ] ; then
	# Gentoo EAPI 7+
	: ${PKG_CONFIG_SYSROOT_DIR=${SYSROOT}}
	PREFIX=${ESYSROOT%/}
	PREFIX=${PREFIX#${SYSROOT%/}}
elif [ -n "${ROOT+x}" ] ; then
	# Gentoo EAPI 0-6
	if [ -n "${SYSROOT%/}" ]; then
		: ${PKG_CONFIG_SYSROOT_DIR=${SYSROOT}}
		PREFIX=${EPREFIX%/}
	else
		: ${PKG_CONFIG_SYSROOT_DIR=}
		PREFIX=${PORTAGE_OVERRIDE_EPREFIX%/}
	fi
elif [ -n "${SYSROOT+x}" ] ; then
	# Generic
	: ${PKG_CONFIG_SYSROOT_DIR=${SYSROOT}}
elif [ "@CROSS_PKG_CONFIG_INSTALLED@" = "installed" ] ; then
	# Manual install
	: ${PKG_CONFIG_SYSROOT_DIR="@CROSS_PKG_CONFIG_PATH@"}
elif [ -n "${STAGEDIR}" ] ; then
	# uClinux-dist
	: ${PKG_CONFIG_SYSROOT_DIR=${STAGEDIR}}
	PKG_CONFIG_LIBDIR=${UCLINUX_PKG_CONFIG_LIBDIR}
else
	# /usr/<target>
	: ${PKG_CONFIG_SYSROOT_DIR=/usr/${CHOST}}

	if [ -z "${CHOST}" ] || [ ! -d "${PKG_CONFIG_SYSROOT_DIR}" ] ; then
		error "Need \$ROOT or \$STAGEDIR set first"
	fi
fi

export PKG_CONFIG_SYSROOT_DIR=${PKG_CONFIG_SYSROOT_DIR%/}
PKG_CONFIG_ESYSROOT_DIR=${PKG_CONFIG_SYSROOT_DIR}${PREFIX}

# https://github.com/pkgconf/pkgconf/issues/205
export PKG_CONFIG_FDO_SYSROOT_RULES=1

#
# Some distributions pollute the pkg-config environment.
# Time to pull a captain planet on them.
#
unset PKG_CONFIG_PATH

#
# Try and figure out the appropriate libdir for this target.
# This logic matches Gentoo's get_libdir which uses $ABI.
#
: ${ABI:=${DEFAULT_ABI:-default}}
var="LIBDIR_${ABI}"
eval libdir=\${${var}}
if [ -z "${libdir}" ] ; then
	# Fall back to probing the compiler.
	## TODO: CLANG FIX
	libdir=$(realpath "$(${CC:-${CHOST}-gcc} ${CFLAGS} ${LDFLAGS} -print-file-name=pkgconfig)/..")
	# Chopping the basename isn't exactly correct, but it's good enough for now.
	libdir=${libdir##*/}
fi
: ${libdir:=lib}
export \
	PKG_CONFIG_SYSTEM_LIBRARY_PATH="${PKG_CONFIG_ESYSROOT_DIR}/usr/${libdir}:${PKG_CONFIG_ESYSROOT_DIR}/${libdir}" \
	PKG_CONFIG_SYSTEM_INCLUDE_PATH="${PKG_CONFIG_ESYSROOT_DIR}/usr/include"

#
# Set the pkg-config search paths to our staging directory.
#
PKG_CONFIG_LIBDIR="${PKG_CONFIG_LIBDIR}${PKG_CONFIG_LIBDIR:+:}${PKG_CONFIG_ESYSROOT_DIR}/usr/${libdir}/pkgconfig:${PKG_CONFIG_ESYSROOT_DIR}/usr/share/pkgconfig"

#
# Sanity check the output to catch common errors that do not
# cause failures until much later on.
#
output=$("${REAL_PKG_CONFIG}" "$@")
ret=$?

# We turn the output into a newline separate string of options, then use grep
# to look for bad -Is and -Ls.  Bad -Is and -Ls are ones that point to things
# outside the ${PKG_CONFIG_ESYSROOT_DIR}.
bad_lines=$(
	printf "%s\n" ${output} |                # Put each flags on its own line.
	grep '^-[LI]' |                          # Find all -I and -L lines.
	grep -v "^..${PKG_CONFIG_ESYSROOT_DIR}"  # Find all things outside the sysroot.
)
if [ -n "${bad_lines}" ] ; then
	warn "### falling down so here is a dump state ######"
	"${REAL_PKG_CONFIG}" --debug "$@" 1>&2
	warn "### end of dump ###############################"
	warn "### suspicious compile flags dumped here ######"
	printf "%s\n" "${bad_lines}"
	warn "### end of flag dump ##########################"
	error "host -I or -L paths detected: ${output}"
fi
[ -n "${output}" ] && printf "%s\n" "${output}"
exit ${ret}
