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

set -e

DUNE2_DATA="http://devs.opendune.org/~truebrain/releases/opendune-data.tar.bz2"
DUNE2_SCENARIO="http://forum.opendune.org/download/file.php?id=6"
DUNE2_SCENARIO_LEN=312224

download_with_progress() {
    if [ $# -lt 2 ]; then return; fi
    URL=$1
    TARGET=$2
    
	wget $DUNE2_DATA 2>&1 \
	| sed 's/.*\ \([0-9]\+%\)\ \+\([0-9.]\+\ [KMB\/s]\+\)$/\1\n# Downloading \2/' \
	| zenity --progress --auto-close --auto-kill --title="Downloading Dune II Data 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)
	if [ ! -L /opt/maemo/usr/share/games/opendune/data ]; then
		mkdir -p /home/user/MyDocs/Games/DUNE2
		mv -f /opt/maemo/usr/share/games/opendune/data/* /home/user/MyDocs/Games/DUNE2/ || true
		rmdir /opt/maemo/usr/share/games/opendune/data
		ln -s /home/user/MyDocs/Games/DUNE2 /opt/maemo/usr/share/games/opendune/data
	fi

	if [ ! -r /home/user/MyDocs/Games/DUNE2/scenario.pak ]; then
		DATAFILE="opendune-data.tar.bz2"
		SCENARIOFILE="scenario.pak"
		
		cd /home/user/MyDocs/Games/DUNE2
		if [ -r "$SCENARIOFILE" && "$(ls -l $SCENARIOFILE | cut -d' ' -f5)" -ne $DUNE2_SCENARIO_LEN ]; then
			rm -f $SCENARIOFILE
			download_with_progress "$DUNE2_SCENARIO" "$SCENARIOFILE"
		fi

		rm -f $DATAFILE
		download_with_progress "$DUNE2_DATA" "$DATAFILE"
		bzcat $DATAFILE | tar x
		if [ ! -r opendune-data/data/scenario.pak || ! -r $SCENARIOFILE ]
		then
			zenity --info --text="Downloading Dune II Data files failed."
			exit 1
		fi
		
		rm opendune-data/data/$SCENARIOFILE
		mv opendune-data/data/* ./
		rm -rf opendune-data $DATAFILE
	fi
    ;;

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

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

#DEBHELPER#

exit 0

