#!/bin/bash -e
set -o pipefail  # note: pipefail is a bashism

# Configuration
# TODO: configure absolute paths at install
LD='/opt/local/bin/ld-latest'
LD_97='/opt/local/bin/ld-97'
LD_127='/opt/local/bin/ld-127'
PPC_ARCHS='ppc ppc64 ppc750 ppc7400 ppc7450 ppc970'

# Check for -v, -arch, and -macosx_version_min options
for optarg in "$@"; do
	case "$option" in
	-arch)
		arch="$optarg"
		;;
	-macosx_version_min)
		minor_version="${optarg#10.}"
		minor_version="${minor_version%%.*}"
		;;
	esac
	option="$optarg"
	case "$option" in
	-v)
		verbose=1
		;;
	esac
done

# Switch to older ld version for ppc
if [ "$arch" = 'ppc' ]; then
	if [ "$minor_version" -le 4 ] 2>/dev/null; then
		if [ -x "$LD_97" ]; then
			LD="$LD_97"
		else
			printf >&2 'requires ld-97\n'
			exit 1
		fi
	else
		if [ -x "$LD_127" ]; then
			LD="$LD_127"
		elif [ -x "$LD_97" ]; then
			LD="$LD_97"
		else
			printf >&2 'requires ld-127 or ld-97\n'
			exit 1
		fi
	fi
fi

# Add ppc to list of supported archs
if [ $verbose ]; then
	exec 3>&1
	"$LD" "$@" 2>&1 1>&3 3>&- |
		sed "s/^configured to support archs: /&$PPC_ARCHS /" 1>&2 3>&-
else
	exec "$LD" "$@"
fi
