#!/bin/bash
###########################################################################
# Copyright (C) 2015-2021 IoT.bzh Company
#
# Author: Clément Bénier <clement.benier@iot.bzh>
# Author: Romain Forlot <romain.forlot@iot.bzh>
#
# $RP_BEGIN_LICENSE$
# Commercial License Usage
#  Licensees holding valid commercial IoT.bzh licenses may use this file in
#  accordance with the commercial license agreement provided with the
#  Software or, alternatively, in accordance with the terms contained in
#  a written agreement between you and The IoT.bzh Company. For licensing terms
#  and conditions see https://www.iot.bzh/terms-conditions. For further
#  information use the contact form at https://www.iot.bzh/contact.
#
# GNU General Public License Usage
#  Alternatively, this file may be used under the terms of the GNU General
#  Public license version 3. This license is as published by the Free Software
#  Foundation and appearing in the file LICENSE.GPLv3 included in the packaging
#  of this file. Please review the following information to ensure the GNU
#  General Public License requirements will be met
#  https://www.gnu.org/licenses/gpl-3.0.html.
# $RP_END_LICENSE$
###########################################################################

PARENT_COMMAND=$(cat /proc/${PPID}/comm)

function sanitizer() {
	local dirty=$1
	local ret=''
	for val in $(echo $dirty | tr ':' ' ')
	do
		echo $val | grep -E '^/usr/(lib(64)?|include)' && continue
		ret="${ret}:${val}"
	done

	echo ${ret}
}

# If calling process is pkgconfigdeps then don't use the sysroot because this
# command occurs at dependencies generation of rpmbuild. Also don't use the
# sysroot if something is requiring a variable of a directory path.
if echo $PARENT_COMMAND | grep "pkgconfigdeps" &> /dev/null || echo "$@" | grep -P "\-\-variable[ =][_[:alnum:]]*(data|util)dir" &> /dev/null
then
	unset PKG_CONFIG_SYSROOT_DIR
elif echo "$*" | grep -q '\--variable'; then
        unset PKG_CONFIG_SYSROOT_DIR
else
	export PKG_CONFIG_DIR="$CROSS_ROOT/usr/lib/pkgconfig:$CROSS_ROOT/usr/lib64/pkgconfig"$(sanitizer ${PKG_CONFIG_DIR})
	export PKG_CONFIG_DISABLE_UNINSTALLED="yes"
	export PKG_CONFIG_LIBDIR="$CROSS_ROOT/usr/lib/pkgconfig:$CROSS_ROOT/usr/lib64/pkgconfig"$(sanitizer ${PKG_CONFIG_LIBDIR})
	export PKG_CONFIG_PATH="$CROSS_ROOT/usr/lib/pkgconfig:$CROSS_ROOT/usr/lib64/pkgconfig:$CROSS_ROOT/usr/share/pkgconfig"$(sanitizer ${PKG_CONFIG_PATH})
	[ -z "${PKG_CONFIG_SYSROOT_DIR}" ] && export PKG_CONFIG_SYSROOT_DIR="$CROSS_ROOT"
	export PKG_CONFIG_SYSTEM_INCLUDE_PATH="/usr/include"$(sanitizer ${PKG_CONFIG_SYSTEM_INCLUDE_PATH})
	export PKG_CONFIG_SYSTEM_LIBRARY_PATH="/lib:/usr/lib"$(sanitizer ${PKG_CONFIG_SYSTEM_LIBRARY_PATH})
fi

exec pkgconf "$@"

