#!/bin/bash
# entrypoint-override.sh
# Custom entrypoint additions for tapper CS2 game servers.
# This script is called before the CS2 server starts.
# The base image (joedwards32/cs2) handles SteamCMD, CS2 installation, and server launch.

set -e

CS2_DIR="/home/steam/cs2-dedicated"
CSGO_DIR="${CS2_DIR}/game/csgo"

echo "[tapper] Running entrypoint override..."

# --- Ensure correct file permissions on plugin directories ---
# The base image may update CS2 files on boot, which could reset permissions.
# We ensure the steam user owns all addon and config files.
if [ -d "${CSGO_DIR}/addons" ]; then
    echo "[tapper] Setting permissions on addons directory..."
    chmod -R 755 "${CSGO_DIR}/addons"
fi

if [ -d "${CSGO_DIR}/cfg/MatchZy" ]; then
    echo "[tapper] Setting permissions on MatchZy cfg directory..."
    chmod -R 644 "${CSGO_DIR}/cfg/MatchZy/"*.cfg 2>/dev/null || true
fi

# --- Ensure Metamod is registered in gameinfo.gi ---
# The base image may regenerate gameinfo.gi when updating CS2.
# We check and re-patch if needed.
GAMEINFO="${CSGO_DIR}/gameinfo.gi"
if [ -f "${GAMEINFO}" ]; then
    if ! grep -q "csgo/addons/metamod" "${GAMEINFO}"; then
        echo "[tapper] Patching gameinfo.gi to register Metamod:Source..."
        sed -i '/Game_LowViolence/a\\t\t\tGame\tcsgo/addons/metamod' "${GAMEINFO}"
    else
        echo "[tapper] Metamod already registered in gameinfo.gi"
    fi
fi

# --- Write server.cfg additions if not already present ---
SERVER_CFG="${CSGO_DIR}/cfg/server.cfg"
if [ ! -f "${SERVER_CFG}" ] || ! grep -q "tapper server config" "${SERVER_CFG}"; then
    echo "[tapper] Writing server.cfg..."
    cat >> "${SERVER_CFG}" <<'SERVERCFG'
// tapper server config
// Base settings — most are overridden by environment variables from the orchestrator

// Disable bots
bot_quota 0
bot_quota_mode 0

// Performance
sv_maxrate 0
sv_minrate 128000
sv_maxupdaterate 128
sv_mincmdrate 128

// Security
sv_cheats 0
sv_allow_votes 0

// Logging
log on
sv_logbans 1
sv_logecho 1
sv_logfile 1
SERVERCFG
fi

echo "[tapper] Entrypoint override complete."
