#! /bin/bash

# Version 2
# New stuff: 
#  Error checking.
#  Can use lynx if wget isn't found
#  Doesn't run make by default
#  Use sh update-mush --help for new options.

# By Raevnos. Do with it what you will.
# Use at your own risk. No warrenty given or implied.

# Tries to grab a new PennMUSH patch level and install it.
# Run from the base pennmush (Or whatever you renamed it to) directory,
# and it's all automatic.


if [ "$1X" != "X" -a "$1" = "--help" ]; then
    echo "Usage: $0 [--help] [-m]"
    echo "Switches:"
    echo "         --help: Display this message"
    echo "             -m: Run make update; make install if the patch is applied."
    exit 0
fi


# Standard FTP location
GET_FROM=ftp://ftp.pennmush.org
GET_PATH=/pub/PennMUSH/Source

# Standard HTTP location
# GET_FROM=http://ftp.pennmush.org
# GET_PATH=/Source

# Figure out what program to use to get the patchfile
wget --version > /dev/null
if [ $? = 0 ]; then
    GRABBER="wget -q"
else
    lynx --version > /dev/null
    if [ $? = 0 ]; then
	GRABBER="lynx -dump"
    else
	echo "Couldn't figure out a way to grab patchfiles. Install wget!";
	exit 1
    fi
fi


# Get the current mush version
CURRENT=`tail -1 Patchlevel | cut -d ' ' -f4`

MAJOR_VERSION=`echo $CURRENT | cut -dp -f1`
CURRENT_PATCH=`printf "%02d" $(echo $CURRENT | cut -dp -f2)`

echo Currently running PennMUSH ${MAJOR_VERSION}-patch${CURRENT_PATCH} 

# The ugliness in the $(()) is to stop bash from treating the patch number as
# base 8 for small patchnumbers from the leading 0.
NEXT_PATCH=`printf "%02d" $((10#${CURRENT_PATCH} + 1))`

NEW_VERSION="${MAJOR_VERSION}-patch${NEXT_PATCH}"

echo Attempting to retrieve PennMUSH ${NEW_VERSION} from:
echo "           ${GET_FROM}${GET_PATH}"

# Get the patch
eval "${GRABBER} ${GET_FROM}${GET_PATH}/${NEW_VERSION}"

if [ -f $NEW_VERSION ]; then
    # Apply the patch and build
    date > update.log
    echo "Applying $NEW_VERSION" | tee -a update.log
    patch -p1 < $NEW_VERSION | tee -a update.log
    if [ $? != 0 ]; then
	echo "Patch failed! See update.log for details"
        exit 1
    else
	echo "Patch applied."
    fi

    if [ $1 = "-m" ]; then
        echo "Compiling..."
	make update 2>&1 | tee -a update.log && make install 2>&1 | tee -a update.log 
    fi
else
    echo PennMUSH ${NEW_VERSION} was not found.
fi

