#/usr/bin/env bash

SCRIPT_DIR="$( cd "$(dirname "$( readlink -f ${BASH_SOURCE[0]} )")" >/dev/null 2>&1 && pwd)"

export HOME="$SCRIPT_DIR"

export LD_LIBRARY_PATH=".:$LD_LIBRARY_PATH"

IP_INTERNAL="$(ip -o -4 addr show up | awk '!/ lo / {print $4}' | cut -d/ -f1 | head -n1)"

VALVE='hlds_run'
GAME='cstrike'
RENICE=1
RESTART="yes"
BETA_VERSION="$2"
AUTO_UPDATE=""
STEAM="Steam/steamcmd/steamcmd.sh"
STEAMERR="1"

if [ ! -f "$SCRIPT_DIR/serverid.txt" ]; then 2>/dev/null
touch serverid.txt
echo GyHosd73 > serverid.txt
fi

service_install() {
mkdir "$SCRIPT_DIR/custom"
sudo dpkg --add-architecture i386
sudo apt -y install lib32gcc-s1 >/dev/null 2>&1
sudo apt -y install lib32gcc1 >/dev/null 2>&1
sudo apt -y install unzip tar wget screen
wget -O ghrel https://posixbit.net/games/cs16server/ghrel
mkdir -p ~/.local/bin
mkdir -p ~/.ghrel
mv ghrel ~/.ghrel
ln -sf ~/.ghrel/ghrel ~/.local/bin
chmod +x ~/.local/bin/ghrel

	updater
	
echo "[-----------------------------------------------------------------------------]"
echo "[-----------------------------------------------------------------------------]"
echo -e "[---------------------] \033[32m>>> НАЧАЛАСЬ УСТАНОВКА СЕРВЕРА! <<<\033[0m [---------------------]"
echo "[-----------------------------------------------------------------------------]"
echo "[-----------------------------------------------------------------------------]"
	
	ghrel dreamstalker/rehlds
	unzip rehlds-bin-*.zip
	cd bin
	cd linux32
	cp -rf * $SCRIPT_DIR
	cd $SCRIPT_DIR
	rm -rf bin
	rm -rf hlsdk
	rm rehlds-*
	echo -n "90" > steam_appid.txt
	
	ghrel hun1er/rehlds-m
	unzip rehldsm*.zip
	mv -f Linux/* $SCRIPT_DIR
	rm rehldsm*.zip
	
	ghrel rehlds/ReGameDLL_CS
	unzip regamedll-bin-*.zip
	mv -f bin/linux32/cstrike/* $SCRIPT_DIR/cstrike
	rm -rf bin && rm -rf hlsdk && rm regamedll-*
	
	rm $SCRIPT_DIR/cstrike/liblist.gam
	rm $SCRIPT_DIR/libsteam.so
	rm $SCRIPT_DIR/libsteam_api.so
	wget -O $SCRIPT_DIR/cstrike/liblist.gam https://posixbit.net/games/cs16server/liblist.gam
	wget -O $SCRIPT_DIR/libsteam.so https://posixbit.net/games/cs16server/libsteam.so
	wget -O $SCRIPT_DIR/libsteam_api.so https://posixbit.net/games/cs16server/libsteam_api.so
	
	mkdir $SCRIPT_DIR/cstrike/addons
	mkdir $SCRIPT_DIR/cstrike/addons/metamod
	wget -O $SCRIPT_DIR/cstrike/addons/metamod/metamod_i386.so https://posixbit.net/games/cs16server/metamod_i386.so
	wget -O $SCRIPT_DIR/cstrike/addons/metamod/config.ini https://posixbit.net/games/cs16server/config.ini
	
	touch $SCRIPT_DIR/cstrike/addons/metamod/plugins.ini
	echo -e "linux addons/reunion/reunion_mm_i386.so\nlinux addons/reauthcheck/reauthcheck_mm_i386.so\nlinux addons/safenameandchat/SafeNameAndChat.so\nlinux addons/hitboxfixer/hitbox_fix_mm_i386.so\nlinux addons/spread/spread_mm.so\nlinux addons/amxmodx/dlls/amxmodx_mm_i386.so" | tee $SCRIPT_DIR/cstrike/addons/metamod/plugins.ini
	rm $SCRIPT_DIR/cstrike/addons/metamod/metamod.dll
	
	cd $SCRIPT_DIR/cstrike
	rm server.cfg
	wget -O server.cfg https://posixbit.net/games/cs16server/server.cfg
	
	mkdir $SCRIPT_DIR/cstrike/addons/reunion
	mkdir $SCRIPT_DIR/cstrike/addons/reauthcheck
	mkdir $SCRIPT_DIR/cstrike/addons/safenameandchat
	mkdir $SCRIPT_DIR/cstrike/addons/hitboxfixer
	mkdir $SCRIPT_DIR/cstrike/addons/spread
	mkdir $SCRIPT_DIR/cstrike/addons/amxmodx
	
	wget -O $SCRIPT_DIR/cstrike/addons/reunion/reunion_mm_i386.so https://posixbit.net/games/cs16server/reunion_mm_i386.so
	wget -O $SCRIPT_DIR/cstrike/reunion.cfg https://posixbit.net/games/cs16server/reunion.cfg
	wget -O $SCRIPT_DIR/cstrike/addons/reauthcheck/reauthcheck_mm_i386.so https://posixbit.net/games/cs16server/reauthcheck_mm_i386.so
	wget -O $SCRIPT_DIR/cstrike/addons/reauthcheck/reauthcheck.cfg https://posixbit.net/games/cs16server/reauthcheck.cfg
	wget -O $SCRIPT_DIR/cstrike/addons/safenameandchat/SafeNameAndChat.so https://posixbit.net/games/cs16server/SafeNameAndChat.so
	wget -O $SCRIPT_DIR/cstrike/addons/safenameandchat/SafeNameAndChat.cfg https://posixbit.net/games/cs16server/SafeNameAndChat.cfg
	wget -O $SCRIPT_DIR/cstrike/addons/hitboxfixer/hitbox_fix_mm_i386.so https://posixbit.net/games/cs16server/hitbox_fix_mm_i386.so 
	wget -O $SCRIPT_DIR/cstrike/addons/hitboxfixer/hbf.cfg https://posixbit.net/games/cs16server/hbf.cfg
	wget -O $SCRIPT_DIR/cstrike/addons/spread/spread_mm.so https://posixbit.net/games/cs16server/spread_mm.so
	cd $SCRIPT_DIR/cstrike/addons/amxmodx
	wget -O $SCRIPT_DIR/cstrike/addons/amxmodx/amxmodx_190.zip https://posixbit.net/games/cs16server/amxmodx_190.zip
	unzip $SCRIPT_DIR/cstrike/addons/amxmodx/amxmodx_190.zip
	rm $SCRIPT_DIR/cstrike/addons/amxmodx/amxmodx_190.zip
}

service_update() {
    updater
	
	ghrel dreamstalker/rehlds
	unzip rehlds-bin-*.zip
	cd bin
	cd linux32
	cp -rf * $SCRIPT_DIR
	cd $SCRIPT_DIR
	rm -rf bin
	rm -rf hlsdk
	rm rehlds-*
	echo -n "90" > steam_appid.txt
	
	ghrel hun1er/rehlds-m
	unzip rehldsm*.zip
	mv -f Linux/* $SCRIPT_DIR
	rm rehldsm*.zip
}
	
updater() {
    echo "Началась проверка обновлений..."
    sleep 2
		if test -f "$SCRIPT_DIR/$STEAM"; then
			echo "Updating server using STEAM."
			CMD="$SCRIPT_DIR/$STEAM +force_install_dir $SCRIPT_DIR +logon anonymous +app_set_config 90 mod cstrike +app_update 90 +quit";
			if  test -n "$BETA_VERSION"; then
			CMD="$CMD -beta $BETA_VERSION";			
			fi
			
			STEAMEXE=steamcmd $CMD
			if test $? -ne 0; then
				if test -n "$STEAMERR"; then
					echo "Сервер не до конца обновился. Запустите сервер снова для исправления"
					updater
				else
					echo "`date`: STEAM Update failed, ignoring."
					return 0
				fi
			fi
		else
			if test -n "$STEAMERR"; then
				echo "Could not locate STEAM binary:$STEAM, exiting.";
				quit 1
			else
				echo "Could not locate STEAM binary:$STEAM, ignoring.";
				return 0
		fi
	fi
	return 1
	chmod +x hlds_linux
	chmod +x hlds_run
}

if [ -f "$SCRIPT_DIR/hlds_linux" ] || [ -f "$SCRIPT_DIR/hlds_run" ]; then 2>/dev/null
chmod +x hlds_linux
chmod +x hlds_run
chmod +x Steam/steamcmd/linux32/steamcmd
chmod +x Steam/steamcmd/steamcmd.sh
else
service_install
fi

#if [ $IS_PORT_EXISTS != "port" ]; then
#cd cstrike
#wget -O server.cfg https://posixbit.net/games/cs16server/server.cfg
#cd ..
#fi

init() {
while test $# -gt 0; do
	case "$1" in
	"-autoupdate")
	AUTO_UPDATE="yes"
	shift ;;
	esac
	shift
done
}

just_start() {

        if [ -z "$IP_INTERNAL" ]; then
        echo "Ошибка: IP_INTERNAL пуст. Проверьте наличие активного интерфейса."
        exit 1
    fi

    if [ -z "$SCRIPT_DIR" ]; then
        echo "Переменная SCRIPT_DIR не установлена!"
        exit 1
    fi

    CFG_FILE="$SCRIPT_DIR/cstrike/server.cfg"
    BACKUP_FILE="$CFG_FILE.bak"
    TMP_FILE=$(mktemp)

    # Проверим существование server.cfg
    if [ ! -f "$CFG_FILE" ]; then
        echo "Файл server.cfg не найден по пути: $CFG_FILE"
        exit 1
    fi

    echo "IP-адрес сервера: $IP_INTERNAL"

#IP_EXTERNAL="$(curl -s https://ifconfig.me/ip)"
#IS_PORT_EXISTS="$(cat cstrike/server.cfg | grep port | awk 'NR==1 {print $1}')"
SERVERID=`cat serverid.txt | awk 'NR==1 {print $1}'`
    if [ -f "$SCRIPT_DIR/$GAME/$SERVERID.pid" ] || [ -f "$SCRIPT_DIR/$GAME/$SERVERID-screen.pid" ]; then

         if [ "$(ps -p `cat $SCRIPT_DIR/$GAME/$SERVERID-screen.pid` | wc -l)" -gt 1 ]; then
            # Процесс запущен.
            echo -e "\033[33m>>> СЕРВЕР И ТАК УЖЕ БЫЛ ЗАПУЩЕН! <<<\033[0m"
        else.
			if [ "$(ps -p `cat $SCRIPT_DIR/$GAME/$SERVERID-screen.pid` | wc -l)" -gt 1 ]; then
                kill -9 `cat $SCRIPT_DIR/$GAME/$SERVERID-screen.pid`
                echo "Завершение процесса с ID $id"
                echo "Удаление screen pid-файла CS-сервера"
                rm -rf $SCRIPT_DIR/$GAME/$SERVERID-screen.pid
break
            fi
if [ -f $SCRIPT_DIR/$GAME/$SERVERID-screen.pid ]; then
rm -rf $SCRIPT_DIR/$GAME/$SERVERID-screen.pid
fi

        echo "Удаление pid файла CS-сервера"
        rm $SCRIPT_DIR/$GAME/$SERVERID.pid
        screen -wipe 1> /dev/null 2> /dev/null
        service_start
        fi
    else
echo -n > serverid.txt
mktemp csSXXXXXX > serverid.txt && rm csS*
SERVERID=`cat serverid.txt | awk 'NR==1 {print $1}'`
echo rcon_password $SERVERID > cstrike/server_rcon_pass.cfg
cd $SCRIPT_DIR
OPTS="-game $GAME +ip $IP_INTERNAL +exec $SCRIPT_DIR/cstrike/server.cfg -pidfile $SCRIPT_DIR/$GAME/$SERVERID.pid"
        if [ -x $SCRIPT_DIR/$VALVE ]; then
			INTERFACE="screen -A -m -d -S $SERVERID"
            $INTERFACE $SCRIPT_DIR/$VALVE $OPTS
            sleep 1
            ps -ef | grep SCREEN | grep "$SERVERID" | grep -v grep | awk '{ print $2}' > $SCRIPT_DIR/$GAME/$SERVERID-screen.pid
			echo "[-----------------------------------------------------------------------------]"
			echo "[-----------------------------------------------------------------------------]"
			echo -e "[---------------------] \033[32m>>> СЕРВЕР УСПЕШНО ЗАПУЩЕН! <<<\033[0m [---------------------]"
			echo "[-----------------------------------------------------------------------------]"
			echo "[-----------------------------------------------------------------------------]"
			echo " "
#			echo -e "ВАЖНО! Не забудьте изменить IP сервера в \033[1m\033[36mserver.cfg\033[0m на ваш \033[1m\033[36m$IP_ITERNAL\033[0m!"
			echo -e "Команда вызова консоли: \033[1m\033[36mscreen -r $SERVERID\033[0m (свернуть: CTRL A, затем CTRL D)\033[0m"
			echo " "
			sleep 1
            chmod 666 $GAME/*.pid #1> /dev/null 2> /dev/null
            chown $USER $GAME/*.pid #1> /dev/null 2> /dev/null
            sleep 2
            if [ $RENICE = 1 ]; then
                renice -20 `cat $SCRIPT_DIR/$GAME/$SERVERID.pid` >/dev/null 2>&1
    fi
fi
fi
}

init $*

service_start() {
	if test -n "$AUTO_UPDATE"; then
	echo "[-----------------------------------------------------------------------------]"
	echo "[-----------------------------------------------------------------------------]"
	echo -e "[-----------]\033[33m >>> ПРОВЕРКА ОБНОВЛЕНИЙ СЕРВЕРА COUNTER-STRIKE! <<<\033[0m [-----------]"
	echo "[-----------------------------------------------------------------------------]"
	echo "[-----------------------------------------------------------------------------]"
	sleep 5
	service_update
	just_start
	else
	just_start
fi
}

service_stop() {
SERVERID=`cat serverid.txt | awk 'NR==1 {print $1}'`
    if [ -f $SCRIPT_DIR/$GAME/$SERVERID-screen.pid ]; then
        for id in `cat $SCRIPT_DIR/$GAME/$SERVERID-screen.pid`
            do kill -9 $id 2>/dev/null
            echo "Завершение процесса $id"
            echo "Удаление screen.pid"
            rm -rf $SCRIPT_DIR/$GAME/$SERVERID-screen.pid
            break
        done
        echo "Удаление pid"
        rm -rf $SCRIPT_DIR/$GAME/$SERVERID.pid
		echo -n > cstrike/server_rcon_pass.cfg
        screen -wipe 1> /dev/null 2> /dev/null
        echo -e "\033[1;91m>>> СЕРВЕР УСПЕШНО ВЫКЛЮЧЕН! <<<\033[0m"
		sleep 1
    else
        echo -e "\033[1;91m>>> СЕРВЕР И ТАК УЖЕ БЫЛ ВЫКЛЮЧЕН! <<<\033[0m"
        #exit 1
    fi    
}    

case "$1" in
    'start')
        service_start
        ;;
    'stop')
        service_stop
        ;;
    'restart')
        service_stop
        sleep 1
        service_start
        ;;
    'update')
        service_update
        ;;
	'install')
        service_install
        ;;
    *)
	echo "Использовать так: $0 start, либо $0 stop, либо $0 restart, либо $0 update"
esac
