#! /bin/bash
# Redirect gcc to look in the native sysroot BEFORE the standard directories
#
# WARNING: this script must not output anything, this may crash autoconf scripts
#
# NOTE: this script is installed in $INSTALL/usr/bin (here INSTALL is usually directly sysroot)
#
: ${use_verbose_compiler:=false}
verbose=$use_verbose_compiler

here=$(pwd)
cd $(dirname $0)
there=$(pwd)
cd $here

installdir=${there%/usr/bin}
configdir=${installdir}/etc
usrbindir=${installdir}/usr/bin
platform=${there%%/sysroots/native/*}
workspace=$(dirname $platform)

cmdname=${0##*/}
tool=${cmdname##*-}
toolname=${tool//+/P}

workSubDir=${here#${workspace%/}/}
if [ "$workSubDir" = "$here" ]; then
	workDir=$here
	workSubDir="."
else
	workDir=$workspace/${workSubDir%%/*}
	workSubDir=${workSubDir#*/}
fi

sysrootDir=${there%/usr/bin}
if [ ! -d $sysrootDir/usr/bin ]; then
	echo "'$0' is not located in /usr/bin of a native sysroot but in '$there'..."
	exit 1
fi

configdir=${sysrootDir}/etc
usrbindir=/usr/bin
platform=${sysrootDir%/sysroots/native}
manifest=$platform/ac6_platform_manifest.xml
if [ "$sysrootDir" != "$platform/sysroots/native" -o ! -r $manifest ]; then
	echo "'$0' is not located in /usr/bin of the native sysroot of a valid SW4L platform..."
	exit 1
fi

#
# Get architecture options from the platform manifest
#
# This should be provided in the environment, but getting these manually
# allows to use the compiler without being started by the platform,
# thus allowing to use this compiler in CDT projects for example,
# the only thing needed being to have the native sysroot in the PATH
#
arch_env=$configdir/native-gcc.env
if [ $manifest -nt $arch_env ]; then
	rm -f $arch_env
	mkdir -p $configdir
	tmpbase=/tmp/native-gcc.$$
	cat << EOF > $tmpbase.sed
<config langId="fr.ac6.platform.arch.native.settings">,/<\/config>/{
s/^.*<property name="\([a-zA-Z0-9_]\+\)"[^>]*>\(.*\)<\/property>.*$/\1="\2"/p
}
EOF
	sed -n -f $tmpbase.sed $manifest > $arch_env
fi
if [ ! -r $arch_env ]; then
	echo "Not in a native sysroot... Bail out!" >&2
	exit 1
fi
. $arch_env

tool_options="${toolname}_options"
tool_options="${!tool_options}"

if [[ "$tool" =~ "++" ]]; then
	cPP_includes="/usr/include/c++"
	cPP_libdirs=""
fi
c_includes="/usr/include"
c_libdirs="/usr/lib /lib"

declare -a options Ldirs Idirs
nb_options=0
nb_Ldirs=0
nbIdirs=0

#
# Simplify a path, suppressing .. and . references, as long as the referenced
# directory, is still the same
# 
simplify_path() {
	local path="$1/"
	path="${path//\/.\///}"
	path="${path//\/.\///}"
	path="${path//\/.\///}"
	path="${path//\/.\///}"
	path="${path//\/.\///}"
	path="${path//\/\///}"
	path="${path//\/\///}"
	path="${path//\/\///}"
	path="${path//\/\///}"
	path="${path//\/\///}"
	local start end base

	while [[ " $path" =~ " ../" ]]; do
		base="../$base"
		path=${path#../}
	done
	while true; do
		start=${path%%/../*}
		if [ "$start" = "$path/" ]; then break; fi
		if [ -z "$base$start" ]; then
			path=${path#/..} # /.. is /
			continue
		fi
		if [ ! -d "$base$start" ]; then break; fi
		end=${path#*/../}
		if [ "$base$start/.." -ef "${base%/}/${start%/*}" ]; then
			path="${start%/*}"/$end
		else
			break
		fi
	done
	echo $base$path | sed -e 's://*$::'
}

add_include_directory() {
	local Idir
	for Idir; do
		Idir_orig=$(simplify_path $Idir)
		Idir=${Idir_orig#$sysrootDir}
		if [[ " ${Idirs[*]} " =~ " $Idir " ]]; then
			continue
		fi
		Idirs[nb_Idirs++]=$Idir
		case $Idir in
			/*)
				# Only prefix absolute paths by the sysroot
				if [ -d "$sysrootDir$Idir" ]; then 
					options[nb_options++]="-I$sysrootDir$Idir"
				fi
				;;
		esac
		if [ -d "$Idir" ]; then 
			options[nb_options++]="-I$Idir"
		fi
	done
}

add_library_directory() {
	local Ldir
	for Ldir; do
		Ldir_orig=$(simplify_path $Ldir)
		Ldir=${Ldir_orig#$sysrootDir}
		if [[ " ${Ldirs[*]} " =~ " $Ldir " ]]; then
			continue
		fi
		Ldirs[nb_Ldirs++]=$Ldir
		case $Ldir in
			/*) 
				# Only prefix absolute paths by the sysroot
				if [ -d "$sysrootDir$Ldir" ]; then 
					options[nb_options++]="-L$sysrootDir$Ldir"
					case $tool in
						gcc | cc | g++ | c++)
							options[nb_options++]="-Wl,-rpath,$sysrootDir$Ldir"
							;;
						ld | ld-*)
							options[nb_options++]="-rpath"
							options[nb_options++]="$sysrootDir$Ldir"
							;;
					esac
				fi
				;;
		esac
		if [ -d "$Ldir" ]; then 
			options[nb_options++]="-L$Ldir"
			
			# Loading libraries with relative path will only work once installed for static libraries
			# We should not generate the RPATH for relative RPATHS (the developer should have taken care
			# if he needs to execute from the build environment) nor for paths outside the native sysroot
			# (these should be added globally to be simply usable...)
			# Just keep the code for now for reference...
#			case $tool in
#				gcc | cc | g++ | c++)
#					options[nb_options++]="-Wl,-rpath,$Ldir"
#					;;
#				ld | ld-*)
#					options[nb_options++]="-rpath"
#					options[nb_options++]="$Ldir"
#					;;
#			esac
		fi
	done
}

case $tool in
	gcc | cc | g++ | c++ | as | cpp | ld | ld-*)
		# For these tools some options must be tailored to fit the target and sysroot, and conflicts
		# with values set in the global architecture options must be resolved in favor of local options
		pass_next=false
		opt=""
		for option in "$@"; do
			if $pass_next; then
				pass_next=false
			else
				# set opt and trim option
				case $option in
					-I | -L)
						pass_next=true
						opt=$option
						continue
						;;
					-I*)
						opt=-I
						option=${option#-I}
						;;
					-L*)
						opt=-L
						option=${option#-L}
						;;
					-Wl,-rpath,*) # Replace explicit -rpath by -L, as the RPATH will be regenerated later on
						opt=-L
						option=${option#-Wl,-rpath,}
						;;
					-print-* | -dump* | --version | --help | --help-* | --target-help)
						verbose=false # Never print more than what is requires...
						opt=other
						options[nb_options++]="$option"
						continue
						;;
					*)
						opt=other
						options[nb_options++]="$option"
						continue
						;;
				esac
			fi
			case $opt in
				-I)
					if [[ " $cPP_includes $c_includes " =~ " $option " ]]; then
						# Ignore standard directories, as they will be added as default directories later on
						continue
					fi
					add_include_directory "${option}"
					;;
				-L)
					if [[ " $cPP_libdirs $c_libdirs " =~ " $option " ]]; then
						# Ignore standard directories, as they will be added as default directories later on
						continue
					fi
					add_library_directory "${option}"
					;;
			esac
		done
		;;
	*)
		for option in "$@"; do
			options[nb_options++]="$option"
		done
		;;
esac

case $tool in
	gcc | cc | g++ | c++)
		add_include_directory $cPP_includes $c_includes
		add_library_directory $cPP_libdirs $c_libdirs
		;;
	as | cpp)
		add_include_directory $cPP_includes $c_includes
		;;
	ld | ld-*)
		add_library_directory $cPP_libdirs $c_libdirs
		;;
esac

$verbose && (echo $(basename $0) CALLED AS: $0 "$@" >&2; \
             echo $(basename $0) REWRITTEN: ${usrbindir}/${tool} ${tool_options} "${options[@]}") >&2
export use_verbose_compiler=$verbose
exec ${usrbindir}/${tool} ${tool_options} "${options[@]}"