#!/usr/bin/env bash

if [ -r /cygdrive/. ]; then
	winpath2unix() { cygpath -u "$1"; }
	unixpath2win() { cygpath -w "$1"; }
fi

link_dirs=()
opts=()
chost="@GENTOO_PORTAGE_CHOST@"
prefix="@GENTOO_PORTAGE_EPREFIX@"
absprefix=${prefix}
if [[ ${CHOST} == *"-winnt"* ]]; then
    # we may get called from windows binary, like pkgdata in dev-libs/icu
    # in this case, PATH elements get the "/dev/fs/C/WINDOWS/SUA" prefix
    absprefix=$(winpath2unix "$(unixpath2win "${absprefix}")")
fi
[[ $0 == *windres* ]] && mode=compile || mode=link
orig_args=("$@")

for opt in "$@"; do
 case "$opt" in
  -L)	link_dirs=("${link_dirs[@]}" "-L$1"); shift ;;
  -L*)	link_dirs=("${link_dirs[@]}" "${opt}") ;;
  *)
  	case "${opt}" in
	-v)	
		# -v done right: only use mode version if -v is the _only_
		# argument on the command line.
		[[ ${#orig_args[@]} -gt 1 ]] || mode=version
		;;
	--version)	mode=version ;;
	-c|-E|-S)	mode=compile ;;
	-print-search-dirs) mode=dirs ;;
	esac
  	opts=("${opts[@]}" "${opt}")
	;;
 esac
done

save_ifs=$IFS
IFS=':'
new_path=
for p in $PATH; do
 IFS=$save_ifs
 [[ "${p#${absprefix}}" != "${p}" ]] && continue
 if [[ -z "${new_path}" ]]; then
  new_path="${p}"
 else
  new_path="${new_path}:${p}"
 fi
done
IFS=$save_ifs

PATH=${new_path}

# toolchain-prefix-wrapper's ld-wrapper understands '-R' for aix and hpux too.
# parity (winnt) understands -rpath only ...
case "${chost}" in
*-winnt*) rpath_opt="-Wl,-rpath," ;;
*) rpath_opt="-Wl,-R," ;;
esac

pfx_link=("-L${prefix}/usr/lib" "-L${prefix}/lib")
pfx_link_r=("${rpath_opt}${prefix}/lib" "${rpath_opt}${prefix}/usr/lib")
pfx_comp=("-I${prefix}/include" "-I${prefix}/usr/include")

case "$mode" in
link)      exec "$(basename $0)" "${link_dirs[@]}" "${pfx_link[@]}" "${opts[@]}" "${pfx_comp[@]}" "${pfx_link_r[@]}" ;;
compile)	exec "$(basename $0)" "${link_dirs[@]}" "${opts[@]}" "${pfx_comp[@]}" ;;
version)	exec "$(basename $0)" "${orig_args[@]}" ;;
dirs)
	"$(basename $0)" "${orig_args[@]}" | while read line; do
		if [[ "${line}" == "libraries: ="* ]]; then
			echo "libraries: =${prefix}/usr/lib:${prefix}/lib:${line#"libraries: ="}"
		else
			echo "${line}"
		fi
	done
	;;
*)			echo "cannot infer $0's mode from comamnd line arguments"; exit 1 ;;
esac

