#!/usr/bin/env bash

GREEN='\033[0;32m'
BLUE='\033[0;33m'
NC='\033[0m'

replace_variable () {
    echo -e "${BLUE}Setting $2 to $3 in $1"
    mv $CSGOSERVER/csgo/cfg/$1 $CSGOSERVER/csgo/cfg/$1.tmp
    cat $CSGOSERVER/csgo/cfg/$1.tmp | grep -v $2 > $CSGOSERVER/csgo/cfg/$1
    echo "$2 $3" >> $CSGOSERVER/csgo/cfg/$1
    rm $CSGOSERVER/csgo/cfg/$1.tmp
}

if [[ ! -f "$HOME/Steam/steamcmd.sh" ]]; then
    echo -e "${BLUE}Steam not found, downloading${NC}"
    curl -fsSL https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz | tar -C $HOME/Steam -xz
    echo -e "${GREEN}Steam downloaded and extracted to $HOME/Steam${NC}"
fi

if [[ $RUNSCRIPT ]]; then
    Steam/steamcmd.sh +runscript $HOME/csgo_ds.txt
fi

if [[ ! -d "$CSGOSERVER/csgo/addons/metamod" ]]; then
    echo -e "${BLUE}Metamod not installed, downloading v$METAMODVERSION${NC}"
    curl -fsSL "https://www.metamodsource.net/latest.php?version=$METAMODVERSION&os=linux" | tar -C $CSGOSERVER/csgo -xz
    echo -e "${GREEN}Metamod installed.${NC}"
fi

if [[ ! -d "$CSGOSERVER/csgo/addons/sourcemod" ]]; then
    echo -e "${BLUE}Sourcemode not installed, downloading v$SOURCEMODVERSION${NC}"
    curl -fsSL "http://sourcemod.net/latest.php?version=$SOURCEMODVERSION&os=linux" | tar -C $CSGOSERVER/csgo -xz
    echo -e "${GREEN}Sourcemod installed.${NC}"
fi

if [[ -f "/server/server.cfg" ]]; then
    echo -e "${BLUE}Moving server.cfg${NC}"
    mv /server/server.cfg $CSGOSERVER/csgo/cfg/server.cfg
fi

if [[ -f "/server/autoexec.cfg" ]]; then
    echo -e "${BLUE}Moving autoexec.cfg${NC}"
    mv /server/autoexec.cfg $CSGOSERVER/csgo/cfg/autoexec.cfg
fi

if [[ $RCON_PASSWORD ]]; then
    echo -e "default:\n  address: \"127.0.0.1:27015\"\n  password: \"${RCON_PASSWORD}\"" > "$HOME/rcon.yaml"
    replace_variable "autoexec.cfg" "rcon_password" "\"$RCON_PASSWORD\""
fi

if [[ $SERVER_PASSWORD ]]; then
    replace_variable "autoexec.cfg" "sv_password" "\"$SERVER_PASSWORD\""
fi

if [[ $SERVER_HOSTNAME ]]; then
    replace_variable "autoexec.cfg" "hostname" "\"$SERVER_HOSTNAME\""
fi

if [[ $TICKRATE ]]; then
    replace_variable "server.cfg" sv_mincmdrate $TICKRATE
    replace_variable "server.cfg" sv_maxcmdrate $TICKRATE
fi

echo -e "${GREEN}Starting csgo${NC}"
csgo/srcds_run -game csgo -tickrate $TICKRATE -autoupdate -steam_dir $CSGOSERVER/csgo \
-steamcmd_script $CSGOSERVER/csgo/csgo_ds.txt -console -usercon +sv_setsteamaccount $STEAMTOKEN \
-net_port_try 1 $STARTARGS