#!/bin/sh
BASENAME=`basename $0`
export SDL_VIDEO_X11_WMCLASS=${BASENAME}
DIALOG_PATH=`tempfile`
DIALOG_TITLE=""
DATA_PATH=""
MMC1_PATH=/media/mmc1/share/sw
MMC2_PATH=/media/mmc2/share/sw

show_dialog() {
	maemo-confirm-text "$DIALOG_TITLE" $DIALOG_PATH
}

ask_download() {
	cat <<EOF > $DIALOG_PATH
Would you like to download Shadow Warrior data files now?

You can download files later or download them manually
from http://www.3drealms.com/sw/

If you choose to download files manually, you need file
called 3dsw12.zip and from there you have to extract 
file called SW.GRP. SW.GRP has to be placed to either
/media/mmc1/share/sw/sw.grp or /media/mmc2/share/sw/sw.grp

If you have your own copy of Shadow Warrior game you
can use data files from CD too.
EOF
	DIALOG_TITLE="Download data files now?"
	show_dialog
}

ask_path() {
	cat <<EOF > $DIALOG_PATH
Answer "OK" to install data files to Internal Memory Card
Answer "Cancel" to install data files to External Memory Card

Data files have their own license, which can be reviewed after
installing from memory card install directory.
EOF
	DIALOG_TITLE="Select memory card"
	show_dialog
	if [ $? == 0 ]; then
		DATA_PATH=$MMC2_PATH
	else
		DATA_PATH=$MMC1_PATH
	fi
}

download() {
	cd $DATA_PATH
	rm -f $DATA_PATH/3dsw12.zip
	osso-xterm -e "wget -P $DATA_PATH ftp://ftp.3drealms.com/share/3dsw12.zip"
	unzip -o $DATA_PATH/3dsw12.zip SWSW12.SHR
	rm -f $DATA_PATH/3dsw12.zip
	unzip -o $DATA_PATH/SWSW12.SHR SW.GRP LICENSE.TXT
	rm -f $DATA_PATH/SWSW12.SHR
	mv $DATA_PATH/SW.GRP $DATA_PATH/sw_.grp
	mv $DATA_PATH/sw_.grp $DATA_PATH/sw.grp
}


card_error() {
        cat <<EOF > $DIALOG_PATH
Memory card not found. Installation aborted.
EOF
        DIALOG_TITLE="Card not found"
        show_dialog
}

check_card() {
	if [ "$DATA_PATH" == "$MMC2_PATH" ]; then 
		if [ `gconftool-2 --get /system/osso/af/internal-mmc-device-present` == 'false' ] ; then
			card_error
			exit 1
		fi
	else
		if [ `gconftool-2 --get /system/osso/af/mmc-device-present` == 'false' ] ; then
			card_error
			exit 1
		fi
	fi
}

for i in 1 2
do
	if [ -e "/media/mmc$i/share/sw/sw.grp" ]; then 
       		DATA_PATH="/media/mmc$i/share/sw"
	fi
done
if [ "$DATA_PATH" != "" ]; then
	if [ ! -e "$DATA_PATH/sw.cfg" ]; then
		/bin/cp /usr/share/shadowwarrior/sw.cfg $DATA_PATH
		/bin/chown -R user:users $DATA_PATH/sw.cfg
	fi
	cd $DATA_PATH
	/usr/bin/shadowwarriorbin
else
	ask_download
	if [ $? == 0 ]; then
		ask_path
		check_card
		mkdir -p $DATA_PATH
		download
		cp /usr/share/shadowwarrior/sw.cfg $DATA_PATH
		cd $DATA_PATH
		/usr/bin/shadowwarriorbin
	fi
fi
