#!/bin/bash
#
# script to install downloaded maps into UT Maps dir
# Andy Piper <andyp@unrealtournament.org>
# Version 0.2 26/09/2000 
#
# requirements: bash, zip/unzip
#
# I'm sure a lot of this could be done more easily in
# something like perl... but I don't know it (yet ;-)
#
# TODO: - filename case conversion (dm-* => DM-*)
#       - better error handling
#       - zipfile integrity checking
#       - handling / display of zipped readmes
#       - extend to handle skins (?)
#       - ought to do multiple files really...

# set various directory locations
# UTMAPDIR should be edited to point to the Maps directory
UTMAPDIR=/usr/local/games/ut/Maps
#UTMAPDIR=/tmp
# TMPDIR will be used to unzip any compressed files
TMPDIR=/var/tmp/utmap.$$

VERSION=0.2
FILENAME=$1

# function to remove temporary files created by the script
cleanup() {
	rm -rf /var/tmp/utmap.$$
}

# function to display usage information
usage() {
	echo "usage: $0 <mapfile>"
	echo ""
	exit 1
}

# function to install a map
installmapfile() {
	echo "Installing $MAPFILE into $UTMAPDIR..."
	install -m 644 $MAPFILE $UTMAPDIR
	cleanup
    exit 0
}

# function to extract a map from a zipfile
extractmapfile() {

	if [ ! -d $TMPDIR ]; then
		mkdir $TMPDIR
	fi

	echo "Extracting contents of zipfile to temporary directory..."
	unzip -qq -d $TMPDIR $FILENAME

	MAPFILE=`ls $TMPDIR/*.unr`
	installmapfile

    exit 0
}

#
# main script starts here!
#

echo "Unreal Tournament Map installer, v$VERSION..."
echo ""

# check that the UT Maps directory exists
if [ ! -d $UTMAPDIR ]; then
	echo "The directory $UTMAPDIR does not exist:" 
	echo "please edit the location of the Unreal Tournament Maps"
	echo "directory (UTMAPDIR) in the script, and try again."
	exit 1
fi

# check script args
if [ $# -ne 1 ]; then
	usage
elif [ "$1" = "-h" ]; then
	usage
fi

# OK, so does the file itself exist?
if [ ! -f $FILENAME ]; then
	echo "The file $FILENAME was not found."
	exit 1
fi

FILEEXT=`echo $FILENAME | sed 's/.*\.//'`

case $FILEEXT in
 "unr")
	MAPFILE=$FILENAME
	installmapfile
	;;
 "zip")
	extractmapfile
	;;
 *)
	echo "The file does not appear to be a map, or a zipfile."
	exit 1
	;;
esac

exit 0
