#!/bin/bash
#
# -- tribes dedicated server installer
SRVUSER=gameserv
INSBASE=/home/$SRVUSER/.loki/
export TMPBASE=/tmp/tribes2


# -- download the required the files
function get_files {
    if [ ! -f "$TMPBASE/$1" ]
    then
      /usr/bin/wget --no-check-certificate "$2$1" -O "$TMPBASE/$1"
    fi
}


# -- make directories
[ ! -d $TMPBASE ] && mkdir -p $TMPBASE

if [ ! -d $INSBASE ]
then
    mkdir -p $INSBASE/tribes2/Manual
    mkdir -p $INSBASE/tribes2/base/{music,lighting,textures,prefs}
    mkdir -p $INSBASE/tribes2/Classic/scripts/{turrets,weapons,autoexec,packs,vehicles}
	mkdir -p $INSBASE/tribes2/Classic/{logs,stats,serverStats}
fi



# -- download files
get_files t2-linux.zip                   	  "https://www.dropbox.com/s/ejemimzxjdswtvm/"          	        "$TMPBASE"
get_files tribes2-lan-fix-linux.tar.gz        "http://t2.plugh.us/"						        				"$TMPBASE"
get_files classic_v152.zip                    "https://tribes2stats.com/files/mods/"                            "$TMPBASE"


# -- gimme a little time
sleep 1


# -- extract the main installer, the silent installer is a lie!
echo "Installing T2..."
# REMEMBER: There is no GameData in the linux version. Everything is up a dir
[ -f $TMPBASE/t2-linux.zip ] && /usr/bin/unzip -o $TMPBASE/t2-linux.zip -d $TMPBASE/install 2>&1 > /dev/null
# -- move all extract files into place
cp -r $TMPBASE/install/t2-linux/. $INSBASE/tribes2/.
echo "T2 installed!"

echo "Removing old classic version v1.1 from base install"
rm -rf $INSBASE/tribes2/classic


echo "Installing Classic Mod v1.5.2"
# -- update Classic mod to v1.5.2
[ -f $TMPBASE/classic_v152.zip ] && /usr/bin/unzip -o $TMPBASE/classic_v152.zip -d $TMPBASE/classic 2>&1 > /dev/null
[ -f $TMPBASE/classic/classic_files_v152.zip ] && /usr/bin/unzip -o $TMPBASE/classic/classic_files_v152.zip -d $TMPBASE/classic 2>&1 > /dev/null
# -- move all extract files into place
if [ -f $TMPBASE/classic/classic_files_v152.zip ]
then
    mv -f $TMPBASE/classic/base/zz_classic_client_v1.vl2 $INSBASE/tribes2/base/zz_Classic_client_v1.vl2
    cp -r $TMPBASE/classic/classic/. $INSBASE/tribes2/Classic/.
fi


# -- install LAN fix
echo "Installing Tribes2 Lan Fix (Linux)..."
# -- run the sh and output the patched file (tribes2d-lan.dynamic)
if [ -f $TMPBASE/tribes2-lan-fix-linux.tar.gz ]
then
    mkdir -p $TMPBASE/lan-fix
    tar -xzvf $TMPBASE/tribes2-lan-fix-linux.tar.gz -C $TMPBASE/lan-fix 2>&1 > /dev/null
    cp -r $TMPBASE/lan-fix/. $INSBASE/tribes2/.
    cd $INSBASE/tribes2/
    xdelta3 decode -s tribes2d.dynamic tribes2-lan-fix-linux.xdelta tribes2d-lan.dynamic
    chmod 755 tribes2d-lan.dynamic
    echo "Finished setting up T2!"
fi

echo "Binding console.log to container logs"
touch console.log
touch $INSBASE/tribes2/console.log
ln -sf /proc/1/fd/1 console.log
ln -sf /proc/1/fd/1 $INSBASE/tribes2/console.log

exit 0