#!/bin/sh
if [ ! -e $1 ]; then
 echo "Upgrade filename must be given!"
 exit
fi

CWD=`pwd`
F=`readlink -f $1`
cd /usr/local/netams4/

echo "Saving running configuration..."
./jserver/bin/n4ctl savecfg > /dev/null
sleep 3

NOWV=`./jserver/bin/n4ctl version`
NOWT=`stat -c "%y" ./jserver/bin/netams4-jserver.jar | cut -d '.' -f1`

NEWV=`basename $F | sed 's/netams//' | cut -d '-' -f1`
NEWT=`stat -c "%y" $F | cut -d '.' -f1` 

echo "Replacing version $NOWV ($NOWT) to version $NEWV ($NEWT)"

rm -rf tmpcfg
ps ax | grep java | grep netams | awk '{ system("kill " $1) }'
mkdir tmpcfg
mv jserver/db/*.xml jserver/db/*.cfg jserver/db/license.txt netams4.properties tmpcfg
rm -rf doc jserver lib logs radius repserver webadmin

echo "Unpacking new release..."
tar zxvf $F > /dev/null

echo "Moving old files back..."
mv tmpcfg/netams4.properties .
mv tmpcfg/* jserver/db/
# rm -rf tmpcfg

echo "Starting new version...."
./startup.sh

cd $CWD
