#!/bin/bash
# LGSM fn_install_serverfiles function
# Author: Daniel Gibbs
# Website: http://gameservermanagers.com
# Version: 210115

fn_steaminstallcommand(){
counter="0"
while [ "${counter}" == "0" ]||[ "$(grep -wc 0x402 .fn_install_serverfiles.tmp)" -ge "1" ]||[ "$(grep -wc 0x406 .fn_install_serverfiles.tmp)" -ge "1" ]||[ "$(grep -wc 0x6 .fn_install_serverfiles.tmp)" -ge "1" ]||[ "$(grep -wc 0x106 .fn_install_serverfiles.tmp)" -ge "1" ]; do
	counter=$((counter+1))
	if [ "${counter}" -le "10" ]; then
		# Attempt 1-4: Standard attempt
		# Attempt 5-6: Validate attempt
		# Attempt 7-8: Validate, delete long name dir
		# Attempt 9-10: Validate, delete long name dir, re-download SteamCMD
		# Attempt 11: Failure

		if [ "${counter}" -ge "2" ]; then
			fn_printwarningnl "SteamCMD did not complete the download, retrying: Attempt ${counter}:"
		fi

		if [ "${counter}" -ge "7" ]; then
			echo "Removing $(find ${filesdir} -type d -print0 | grep -Ez '[^/]{30}$')"
			find ${filesdir} -type d -print0 | grep -Ez '[^/]{30}$' | xargs -0 rm -rf
		fi
		if [ "${counter}" -ge "9" ]; then
			rm -rf "${rootdir}/steamcmd"
			fn_check_steamcmd
		fi
		if [ "${counter}" -le "4" ]; then
			./steamcmd.sh +login "${steamuser}" "${steampass}" +force_install_dir "${filesdir}" +app_update "${appid}" +quit |tee .fn_install_serverfiles.tmp
		elif [ "${counter}" -ge "5" ]; then
			./steamcmd.sh +login "${steamuser}" "${steampass}" +force_install_dir "${filesdir}" +app_update "${appid}" -validate +quit |tee .fn_install_serverfiles.tmp
		fi
	elif [ "${counter}" -ge "11" ]; then
		fn_printfailurenl "SteamCMD did not complete the download, too many retrys"
		break
	fi

done

# Goldsource servers commonly fail to download all the server files required.
# Validating a few of times may reduce the chance of this issue.
if [ "${engine}" == "goldsource" ]; then
	counter="0"
	while [ "${counter}" -le "4" ]; do
		counter=$((counter+1))
		./steamcmd.sh +login "${steamuser}" "${steampass}" +force_install_dir "${filesdir}" +app_update "${appid}" -validate +quit |tee .fn_install_serverfiles.tmp
	done
fi
rm -f .fn_install_serverfiles.tmp
}

echo ""
echo "Installing ${gamename} Server"
echo "================================="
sleep 1
mkdir -pv "${filesdir}"
cd "${rootdir}/steamcmd"
fn_steaminstallcommand
if [ -z "${autoinstall}" ]; then
	echo ""
	echo "================================="
	while true; do
	read -p "Was the install successful? [y/N]" yn
		case $yn in
			[Yy]* ) break;;
			[Nn]* ) fn_install_retry;;
			* ) echo "Please answer yes or no.";;
		esac
	done
fi