#!/bin/sh
set -e

action="$1"
if [ -n "$action" ]; then
	shift 1
else
	action=on
fi
directory="$2"

writespecs () {
	gcc -dumpspecs > specs.tmp || exit 1
	sed -e 's/\%{mfloat-abi=\*}/%{mfloat-abi=*} %{!mfloat-abi=*:-mfloat-abi=softfp}/' -e 's/\%{profile:-p}/%{profile:-p} %%{!mfloat-abi=*:-mfloat-abi=softfp}/' < specs.tmp > specs || exit 1

	# make sure the sed really modified the file
	if cmp specs specs.tmp >/dev/null; then
		rm -f specs specs.tmp
		echo "* Failed to transform specs file" >&2
		exit 1
	fi
	if ! egrep -q 'mfloat-abi=.*mfloat-abi=softfp' specs ||
	   ! egrep -q 'profile:.*mfloat-abi=softfp' specs; then
		rm -f specs specs.tmp
		echo "* Failed to transform specs file" >&2
		exit 1
	fi
	rm -f specs.tmp
}

arch=$(dpkg --print-architecture)
case "$arch" in
armel)
	;;
arm)
	echo "* an EABI (armel) system is required to use VFP; this system is old abi" >&2
	exit 1
	;;
*)
	echo "* Based on the architecture ($arch), you must be using a cross compiler"
	if [ -z "$directory" ]; then
		echo "* You must specify the GCC library directory to modify." >&2
		echo "  Example: vfp-configure $action /usr/lib/gcc/arm-linux-gnueabi/4.2/" >&2
		exit 1
	fi
	;;
esac

if [ -z "$directory" ]; then
	gccdir=/usr/lib/gcc/arm-linux-gnueabi/$(gcc --version |grep ^gcc | awk '{print $4}')
else
	gzzdir="$directory"
fi
if [ ! -d "$gccdir" ]; then
	echo "* Cannot find gcc directory ($gccdir) -- is gcc installed?" >&2
	exit 1
fi
if [ ! -e "$gccdir/cc1" ]; then
	echo "* Cannot find cc1 inside gcc directory ($gccdir)" >&2
	exit 1
fi
cd /usr/lib/gcc/arm-linux-gnueabi/$(gcc --version |grep ^gcc | awk '{print $4}')

case "$action" in
on)
	if ! writespecs; then
		echo "* Failed to write specs file" >&2
		exit 1
	fi
	echo "VFP compilation enabled (run 'vfp-configure off' to disable)"
	;;
off)
	if [ -e specs ]; then
		if ! rm -f specs; then
			echo "* Failed to remove specs file" >&2
			exit 1
		fi
	fi
	echo "VFP compilation disabled"
	;;
*)
	echo "usage: vfp-configure on|off [directory]" >&2
	exit 1
	;;
esac
