#!/bin/bash
# Location to install the server
PREFIX=/usr/local
# Program to gain access to copy into prefix
SUDO=sudo
# if you have ~/bin on your PATH
#PREFIX=~/
#SUDO=

# Move the updates to ...
UPDATE_DIR=.


# this script assumes the following folder structure:
# This script lives at ./restart.sh

# There is the folder ./eathena, which holds the server sources
# There is the folder ./eathena-data which has content
# There is the folder ./eathena-data/client-data which contains the client data.

# Further on we need a tool called adler32 living at ./adler32 which 
# will sign the zip files (which will contain the updates for clientdata)
# These will start messing up the ./ folder here

# These zip files must be able to get from an updateserver, so either these zip files need to be moved
# to some folder which is properly setup with a http server, or the http server must service this folder.

die()
{
    echo "$@" >&2
    exit 1
}

# killall -0 checks if process exists
# Success is: if we killed it, or if it didn't exist
killall login-server    || ! killall -0 login-server    || die "Failed to kill running login-server"
killall char-server     || ! killall -0 char-server     || die "Failed to kill running char-server"
killall map-server      || ! killall -0 map-server      || die "Failed to kill running map-server"

# get new server binaries
(
cd eathena &&
git pull &&
make
) || die "Failed to update tmwAthena server"

# copy the binaries to the eathena-data
cp ./eathena/login-server "$PREFIX"/bin/
cp ./eathena/char-server "$PREFIX"/bin/
cp ./eathena/map-server "$PREFIX"/bin/

# get new content
cd eathena-data
git pull
(
cd world/map/conf
if ./build-magic.sh | grep updated
then
    echo "You need to update spells"
    echo "exit this subshell to continue"
    bash
    ./build-magic.sh
fi
)

# calculate the update for clients tmwdata
cd client-data || die "No client data found"
#caclulate the commits which got added
previous=`git log --pretty=format:%h -n 1`
(
    cd .. &&
    git submodule update
) || die "Failed to update client-data"
head=`git log --pretty=format:%h -n 1`
# get the filelist and zip those files
ZIPNAME=update-${previous}..${head}.zip
git log --name-only ${previous}..${head} | sort -u | xargs zip -9 ../../$ZIPNAME || die "Could not calculate/generate updates"
cd ../..
# append the zip file to resources2.txt
# What about resources.xml?
if [ -f $ZIPNAME ]; then
    ./adler32 $ZIPNAME >> "$UPDATE_DIR"/resources2.txt &&
    mv $ZIPNAME "$UPDATE_DIR" || die "Could not package updates"
fi

cd eathena-data
# These are scripts now, not the servers directly
./login-server &
./char-server &
./map-server &
