#!/bin/bash
#
# Script to install or remove the AmigaOS include files to or from ${CROSS_ROOT}
# by downloading and extracting the official SDK.
#
# (c) 2014 by Sebastian Bauer
#

set -e

# Root of the cross compiler environment
CROSS_ROOT=/usr/

# Usage
display_usage() {
	echo "Usage:"
	echo "  update-adtools-sdk-nonfree --install"
	echo "  update-adtools-sdk-nonfree --uninstall"
	exit 1
}

# Parse options
GETOPT_RESULT=`getopt --longoptions install,uninstall --options iu -n update-adtools-sdk -- "$@"` || display_usage
eval set -- "${GETOPT_RESULT}" || display_usage

case "$1" in

	--install)
		# Temporary directory that will contain extracted stuff
		EXTRACTDIR=`mktemp -d /tmp/adtools-sdk.XXXXXXXXXXX`

		wget "http://www.hyperion-entertainment.biz/index.php?option=com_registration&amp;view=download&amp;format=raw&amp;file=69&amp;Itemid=63" -O ${EXTRACTDIR}/SDK_53.24.lha
		#cp ../../../native-build/downloads/SDK_53.24.lha ${EXTRACTDIR}/SDK_53.24.lha
		lha xw=${EXTRACTDIR} ${EXTRACTDIR}/SDK_53.24.lha
		lha xw=${EXTRACTDIR} ${EXTRACTDIR}/SDK_Install/base.lha
		lha xw=${EXTRACTDIR} ${EXTRACTDIR}/SDK_Install/clib2-1.205.lha
		lha xw=${EXTRACTDIR} ${EXTRACTDIR}/SDK_Install/newlib-53.28.lha
		mkdir -p ${CROSS_ROOT}/ppc-amigaos/SDK/include

		# Keep information about which files we copied
		(cd ${EXTRACTDIR}; find newlib clib2 -type f | sort | xargs sha1sum >${CROSS_ROOT}/ppc-amigaos/crt.sha1sum)
		(cd ${EXTRACTDIR}/Include; find * -type f | sort | xargs sha1sum >${CROSS_ROOT}/ppc-amigaos/include.sha1sum)

		# Make the files readable for all
		chmod -R a+r ${EXTRACTDIR}

		# Now copy/move the files to the appropriate destination
		mv ${EXTRACTDIR}/clib2* ${EXTRACTDIR}/newlib* ${CROSS_ROOT}/ppc-amigaos/SDK
		mv ${EXTRACTDIR}/Include/* ${CROSS_ROOT}/ppc-amigaos/SDK/include

		;;
	--uninstall)
		(cd ${CROSS_ROOT}/ppc-amigaos/SDK; sha1sum -c ../crt.sha1sum | grep OK$  | cut -d ':' -f 1 | xargs rm)
		(cd ${CROSS_ROOT}/ppc-amigaos/SDK/include; sha1sum -c ../../include.sha1sum | grep OK$  | cut -d ':' -f 1 | xargs rm)
		rm ${CROSS_ROOT}/ppc-amigaos/crt.sha1sum
		rm ${CROSS_ROOT}/ppc-amigaos/include.sha1sum
		find ${CROSS_ROOT}/ppc-amigaos -depth -type d -delete || \
        	echo ${CROSS_ROOT}/ppc-amigaos was not removed as it was not empty
		;;

	*)
		display_usage
		;;
esac

