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

killall login-server
killall char-server
killall map-server

# get new server binaries
cd eathena
git pull
make
cd ..

# copy the binaries to the eathena-data
cp ./eathena/login-server ./eathena-data
cp ./eathena/char-server ./eathena-data
cp ./eathena/map-server ./eathena-data

# get new content
cd eathena-data
git pull
cd conf
cat magic.conf.template | ./spells-build > magic.conf
cd ..
./login-server &
./char-server &
./map-server &
cd ..

# calculate the update for clients tmwdata
cd tmwdata
#caclulate the commits which got added
previous=`git log --pretty=oneline -n 1 | awk '{print $1}'`
git pull
head=`git log --pretty=oneline -n 1 | awk '{print $1}'`
# get the short form of the commit hashes
u1=`echo ${previous} | cut -c 1-7`
u2=`echo ${head} | cut -c 1-7`
# get the filelist and zip those files
git log --name-status ${previous}..${head} | awk '/^(A|M)\t/ {print $2}' | sort | uniq | xargs zip -9 -r ../update-${u1}..${u2}.zip
cd ..
# append the zip file to resources2.txt
if [ -f update-${u1}..${u2}.zip ]; then
  ./adler32 update-${u1}..${u2}.zip >>resources2.txt
fi
