#!/bin/bash

# what are we trying to install?
game_nm=arma3
game_id=233780

profile_location=~/.local/share/"Arma 3 - Other Profiles"/server
profile_name=server.Arma3Profile

# install game to this directory
installdir=/home/steam/games/$game_nm

# if path does not exist, create it
mkdir -p $installdir

if [ "$1" == "update" -o ! -d "$installdir" ]; then
	install="1"
else
	install="0"
fi

if [ "$install" == "1" ] # should we start update or install?
then
	if [ ! -w "$installdir" ]; then
		echo "Cannot write to installation dir."
		exit 1
	fi
	echo "---- Steam login"
	echo -n "Username:"
	read steam_user
	echo -n "Password:"
	read -s steam_password

	# Install or update the game in /home/steam/games/[game name]
	/opt/steamcmd/steamcmd.sh \
		+login $steam_user $steam_password\
		+force_install_dir $installdir \
		+app_update $game_id -beta legacyPorts -betapassword Arma3LegacyPorts validate \
		+quit

	exit 0
else
	# install dir maybe mounted read-only, simply
	# skip installing/updating and inform the user.
	echo "Skipped game installation."
fi

# run the next commands from the installdir
cd $installdir

if [ ! -f "./server.cfg" ]; then
	echo "missing server.cfg, copying default one"
	cp /home/steam/server.cfg .
fi

if [ ! -f "${profile_location}/${profile_name}" ]; then
	echo "missing ${profile_name}, copying default one"
	mkdir -p "${profile_location}"
	cp /home/steam/player.armaProfile "${profile_location}/${profile_name}"
fi

# is the game launcher not executable?
if [ ! -x ./arma3server ]
then
	# we cant run the game then.
	echo "game launcher not found, installed incorrectly?"
	exit 1
fi

# launch the game!
exec ./arma3server -config=server.cfg -mod="mods/@nss_ac" -name=server "$@"