#!/bin/sh
# postinst script for openxcom
#
# see: dh_installdeb(1)

set -e

#ufo.zip
XCOM_DATA_URL="http://old-cans.com/stahuj.php?id=146"
XCOM_PATCH_URL="http://openxcom.org/download/extras/universal-patch.zip"

download_with_progress() {
	if [ $# -lt 3 ]; then return; fi
	URL=$1
	TARGET=$2
	NAME=$3

	wget "$URL" -O"$TARGET" 2>&1 \
	| sed 's/.*\ \([0-9]\+%\)\ \+\([0-9.]\+\ [KMB\/s]\+\)$/\1\n# Downloading \2/' \
	| zenity --progress --auto-close --auto-kill --title="Downloading Xcom $NAME files..." &

	#Start a loop testing if zenity is running, and if not kill wget
	RUNNING=0
	while [ $RUNNING -eq 0 ]
	do
	if [ -z "$(pidof zenity)" ]
	then
		pkill wget | :
		RUNNING=1
	fi
	sleep 1
	done
}

case "$1" in
	configure)
	mkdir -p /home/user/MyDocs/Games/OpenXcom
	
	if [ ! -L /opt/maemo/usr/share/games/openxcom ]; then
		if [ -r /opt/maemo/usr/share/games/openxcom ]; then
			rm -rf /home/user/MyDocs/Games/OpenXcom
			mv -f /opt/maemo/usr/share/games/openxcom /home/user/MyDocs/Games/OpenXcom || true
		fi
		ln -s /home/user/MyDocs/Games/OpenXcom /opt/maemo/usr/share/games/openxcom
	fi

	mkdir -p /home/user/.config/openxcom
	if [ -r /home/user/.config/openxcom/options.cfg ]; then
		sed -i 's/keyBattlePrevUnit: 304/keyBattlePrevUnit: 122/' /home/user/.config/openxcom/options.cfg
	fi
	chown user.users /home/user/.config/openxcom -R || true
	cd /home/user/MyDocs/Games/OpenXcom

	# test random file
	if [ -r maps/ufo_110.map ]; then TEST="maps/ufo_110.map"; fi
	if [ -r maps/UFO_110.MAP ]; then TEST="maps/UFO_110.MAP"; fi
	if [ -r MAPS/ufo_110.map ]; then TEST="MAPS/ufo_110.map"; fi
	if [ -r MAPS/UFO_110.MAP ]; then TEST="MAPS/UFO_110.MAP"; fi

	if [ -z $TEST ]; then
		DATAFILE="ufo.zip"
		TEMPDIR="UFO Enemy Unknown"

		download_with_progress "$XCOM_DATA_URL" "$DATAFILE" Data
		unzip -oqq $DATAFILE > /dev/null 2> /dev/null

		mv -f "$TEMPDIR"/GEODATA . || true
		mv -f "$TEMPDIR"/GEOGRAPH . || true
		mv -f "$TEMPDIR"/MAPS/* MAPS || true
		mv -f "$TEMPDIR"/ROUTES/* ROUTES || true
		mv -f "$TEMPDIR"/SOUND . || true
		mv -f "$TEMPDIR"/TERRAIN . || true
		mv -f "$TEMPDIR"/UFOGRAPH . || true
		mv -f "$TEMPDIR"/UFOINTRO . || true
		mv -f "$TEMPDIR"/UNITS . || true
		rm -rf "$TEMPDIR"
		rm -f $DATAFILE
		TEST="MAPS/UFO_110.MAP"
	fi
	
	if [ $TEST ] && [ -r $TEST ]; then
		# md5sum of patched file
		MD5SUM="6b9f2db7918b5b30b88c03a9db4353b0";
		if [ $MD5SUM != $(md5sum $TEST | cut -d' ' -f1) ]; then
			DATAFILE="universal-patch.zip"
			download_with_progress "$XCOM_PATCH_URL" "$DATAFILE" "Data patch"
			unzip -oqq $DATAFILE > /dev/null 2> /dev/null
			rm -f $DATAFILE
		fi
	fi

	if [ ! -d GEODATA -a ! -d geodata ]; then
		zenity --info --text="Put Xcom data to /home/user/MyDocs/Games/OpenXcom"
		exit 1
	fi

	;;

	abort-upgrade|abort-remove|abort-deconfigure)
	;;

	*)
		echo "postinst called with unknown argument \$1" >&2
		exit 1
	;;
esac



exit 0

