#!/bin/sh 

# Downloads pvpgn support files needed to run the daemon from pvpgn.berlios.de.
#
# (C) 2005 Radu Spineanu <radu@timisoara.roedu.net>
# You may freely distribute this file under the terms of the GNU General
# Public License, version 2 or later.
#

usage() 
{
	echo "usage: pvpgn-support-installer [options]"
	echo "options:
	        -u              -- uninstall
	        -l [path]       -- use local file
	        -d              -- delete archive after install
		-h		-- this message"
}

SUPPORT_PATH="http://download.berlios.de/pvpgn/pvpgn-support-1.0.tar.gz"


# look through input arguments
until [ -z "$1" ]; do
	case $1 in
		"-u") 
			UNINSTALL=1
			;;	
		"-l") 
			# look for the archive
			if [ ! "$2" ]; then
				echo "You need to specify the path to the local file"
				exit 1
			fi
			
			if [ ! -f "$2" ]; then
				echo "Could not find $2"
				exit 1
			fi
			OFFLINE_PATH=$2
			shift
			;;
		"-d")
			DELETE_AFTER=1
			;;
		"-h") 
			usage
			exit
			;;
	    	*   ) 
			usage
			exit
			;;
	esac
	shift
done

echo ""

if [ "$UNINSTALL" ]; then
	echo "Removing support files from /var/lib/pvpgn/files..."
        FILES="IX86ver1.mpq  XMACver1.mpq       bnserver-WAR3.ini  icons.bni
               matchmaking-war3-enUS.dat       PMACver1.mpq  bnserver-D2DV.ini
               bnserver.ini icons_STAR.bni     WAR3IX86.mpq  bnserver-D2XP.ini
               icons-WAR3.bni                  matchmaking-war3-default.dat"
	for i in $FILES; do
		rm -f /var/lib/pvpgn/files/$i
	done
	exit 0
fi

if [ ! $OFFLINE_PATH ]; then # we need wget in order to download the archive
	if [ ! -f "/usr/bin/wget" ]; then
		echo "You need wget in order to download the archive"
		exit 0
	fi
fi
	

# create a temporary work directory
echo "Creating temporary working directory..."
TMPDIR=`mktemp -d -t pvpgn.XXXXXX` || exit 1
cd $TMPDIR

# get the archive
echo "Placing the archive in the temporary directory..."
if [ $OFFLINE_PATH ]; then # copy the archive to the temporary directory
	cp -f $OFFLINE_PATH $TMPDIR/pvpgn-support-1.0.tar.gz
else
	wget $SUPPORT_PATH  || exit 1
fi
 
echo "Unpacking archive..."
tar -xvzf pvpgn-support-1.0.tar.gz || exit 1

echo "Placing files..."
cp -f pvpgn-support-1.0/* /var/lib/pvpgn/files

# cleaning up
if [ "$DELETE_AFTER" ]; then
	echo "Removing temporary directory and archive file.."
	rm -rf $TMPDIR
else
	cp pvpgn-support-1.0.tar.gz /var/lib/pvpgn
	echo "Removing temporary directory.."
	rm -rf $TMPDIR
	if [ ! "$OFFLINE_PATH" ]; then
		echo -e "\n\nThe archive has been saved as /var/lib/pvpgn/pvpgn-support-1.0.tar.gz"
		echo "Use pvpgn-support-installer with the -l flag if you need to reinstall"
	fi
fi

exit 0
