#!/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.
#

FILENAME=pvpgn-support-1.2.tar.gz
SUPPORT_PATH="http://download.berlios.de/pvpgn/${FILENAME}"

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

# 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
 PMACver1.mpq
 XMACver1.mpq
 bnserver-D2DV.ini
 bnserver-D2XP.ini
 bnserver-WAR3.ini
 bnserver.ini
 icons-WAR3.bni
 icons.bni
 icons_STAR.bni
 ver-ix86-1.mpq
  matchmaking-war3-default.dat
  matchmaking-war3-enUS.dat
  WAR3IX86.mpq
"
	for i in $FILES; do
		rm -vf /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 -vf $OFFLINE_PATH $TMPDIR/${FILENAME}
else
	wget $SUPPORT_PATH  || exit 1
fi

echo "Unpacking archive..."
tar -xvzf ${FILENAME} || exit 1

echo "Placing files..."
cp -vf pvpgn-support-1.?/* /var/lib/pvpgn/files

# cleaning up
if [ "$DELETE_AFTER" ]; then
	echo "Removing temporary directory and archive file.."
	rm -rf $TMPDIR
else
	cp -v ${FILENAME} /var/lib/pvpgn
	echo "Removing temporary directory.."
	rm -rf $TMPDIR
	if [ ! "$OFFLINE_PATH" ]; then
		echo
		echo
		echo "The archive has been saved as /var/lib/pvpgn/${FILENAME}"
		echo "Use pvpgn-support-installer with the -l flag if you need to reinstall"
	fi
fi

exit 0
