#!/usr/bin/env bash
set -euo pipefail

BASE="/srv/l2server"
OWNER_USER="devops"
OWNER_GROUP="devops"
OWNER="${OWNER_USER}:${OWNER_GROUP}"

AUTH_DIR="${BASE}/authserver"
GAME_DIR="${BASE}/gameserver"

AUTH_MAIN_PROPS="${AUTH_DIR}/config/authserver.properties"
AUTH_DEF_RU_PROPS="${AUTH_DIR}/config/default_russian/authserver.properties"
AUTH_DEF_EN_PROPS="${AUTH_DIR}/config/default_english/authserver.properties"

log() { echo "[+] $*"; }
warn() { echo "[!] $*" >&2; }
die() { echo "[x] $*" >&2; exit 1; }

need_file() { [[ -f "$1" ]] || die "Файл не найден: $1"; }
need_dir()  { [[ -d "$1" ]] || die "Каталог не найден: $1"; }

# --- Detect external IP (best-effort, no hard fail) ---
detect_external_ip() {
  local ip=""
  # 1) curl with timeout if available
  if command -v curl >/dev/null 2>&1; then
    ip="$(timeout 5s curl -fsS ifconfig.me 2>/dev/null || true)"
  fi
  # 2) fallback: try wget
  if [[ -z "$ip" ]] && command -v wget >/dev/null 2>&1; then
    ip="$(timeout 5s wget -qO- ifconfig.me 2>/dev/null || true)"
  fi
  # Validate (simple IPv4 check)
  if [[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
    echo "$ip"
    return 0
  fi
  echo ""
  return 0
}

log "Проверка структуры..."
need_dir "$BASE"
need_dir "$AUTH_DIR"
need_dir "$GAME_DIR"

# Find server.properties (path can vary)
GAME_SERVER_PROPS="$(find "$GAME_DIR" -maxdepth 5 -type f -name "server.properties" | head -n 1 || true)"
[[ -n "$GAME_SERVER_PROPS" ]] || die "Не найден server.properties в $GAME_DIR (искал до глубины 5)"

log "GameServer server.properties: $GAME_SERVER_PROPS"
need_file "$AUTH_MAIN_PROPS"
need_file "$AUTH_DEF_RU_PROPS"
need_file "$AUTH_DEF_EN_PROPS"

log "Создание log/ директорий..."
sudo mkdir -p "$AUTH_DIR/log" "$GAME_DIR/log"

log "Выставление владельца ${OWNER}..."
sudo chown -R "$OWNER" "$AUTH_DIR" "$GAME_DIR"

log "chmod +x для всех *.sh..."
sudo find "$AUTH_DIR" -type f -name "*.sh" -exec chmod +x {} \; || true
sudo find "$GAME_DIR" -type f -name "*.sh" -exec chmod +x {} \; || true

# --- Patch GameServer properties ---
log "Правка GameServer: DatabaseHost=db, LoginHost=authserver ..."
sudo sed -i \
  -e 's/^\s*DatabaseHost\s*=.*/DatabaseHost = db/' \
  -e 's/^\s*LoginHost\s*=.*/LoginHost = authserver/' \
  "$GAME_SERVER_PROPS"

NEW_IP="$(detect_external_ip)"
if [[ -n "$NEW_IP" ]]; then
  log "Внешний IP определён: $NEW_IP. Обновляю ExternalHostname..."
  sudo sed -i -e "s/^\s*ExternalHostname\s*=.*/ExternalHostname = ${NEW_IP}/" "$GAME_SERVER_PROPS"
else
  warn "Внешний IP не удалось определить (нет ответа/нет curl/wget). ExternalHostname не меняю."
fi

# --- Patch AuthServer main properties ---
log "Правка AuthServer (main): LoginHost=authserver, DatabaseHost=db, DatabaseURL->db, WhiteIpList расширить..."
sudo sed -i \
  -e 's/^\s*LoginHost\s*=.*/LoginHost = authserver/' \
  -e 's/^\s*DatabaseHost\s*=.*/DatabaseHost = db/' \
  -e 's#^\s*DatabaseURL\s*=.*#DatabaseURL = jdbc:mysql://db:3306/interlude?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8#' \
  "$AUTH_MAIN_PROPS"

# WhiteIpList: set explicit value (idempotent)
sudo sed -i \
  -e 's/^\s*WhiteIpList\s*=.*/WhiteIpList = 127.0.0.1,0.0.0.0/' \
  "$AUTH_MAIN_PROPS"

# --- Patch AuthServer default_* properties (LoginHost/DatabaseHost) ---
log "Правка AuthServer default_russian/default_english (LoginHost/DatabaseHost)..."
sudo sed -i \
  -e 's/^\s*LoginHost\s*=.*/LoginHost = authserver/' \
  -e 's/^\s*DatabaseHost\s*=.*/DatabaseHost = db/' \
  "$AUTH_DEF_RU_PROPS" "$AUTH_DEF_EN_PROPS"

# --- Output summary ---
log "Проверка результатов (ключевые строки):"

echo ""
echo "== GameServer =="
grep -nE '^(ExternalHostname|LoginHost|DatabaseHost)\s*=' "$GAME_SERVER_PROPS" || true

echo ""
echo "== AuthServer main =="
grep -nE '^(LoginHost|DatabaseHost|DatabaseURL|WhiteIpList)\s*=' "$AUTH_MAIN_PROPS" || true

echo ""
echo "== AuthServer default_russian =="
grep -nE '^(LoginHost|DatabaseHost)\s*=' "$AUTH_DEF_RU_PROPS" || true

echo ""
echo "== AuthServer default_english =="
grep -nE '^(LoginHost|DatabaseHost)\s*=' "$AUTH_DEF_EN_PROPS" || true

log "Готово."
