#!/usr/bin/env bash
# TeamRally Server — Installations-Skript
# Verwendung: curl -fsSL http://46.224.96.208/download/TeamRally-server/install.sh | bash
set -euo pipefail

BASE_URL="http://46.224.96.208/download/TeamRally-server"
TARBALL="TeamRally-server-latest.tar.gz"
INSTALL_DIR="${1:-TeamRally-server}"

# Hilfsfunktionen
ok()   { echo "  [OK]  $*"; }
info() { echo "  ...   $*"; }
err()  { echo ""; echo "  FEHLER: $*" >&2; echo ""; exit 1; }
ask()  { read -rp "  $1 " "$2"; }

# sudo-Wrapper: funktioniert auch wenn der User root ist
run_as_root() {
    if [ "$(id -u)" = "0" ]; then
        "$@"
    else
        sudo "$@"
    fi
}

echo ""
echo "============================================="
echo "   TeamRally Server -- Installation"
echo "============================================="
echo ""

# ── Betriebssystem erkennen ────────────────────────────────────────────────────
PKG_MGR=""
if command -v apt-get >/dev/null 2>&1; then
    PKG_MGR="apt"
elif command -v dnf >/dev/null 2>&1; then
    PKG_MGR="dnf"
elif command -v yum >/dev/null 2>&1; then
    PKG_MGR="yum"
fi

# ── Python 3 installieren falls noetig ────────────────────────────────────────
info "Pruefe Python 3..."
if ! command -v python3 >/dev/null 2>&1; then
    echo "  Python 3 ist nicht installiert. Installiere es jetzt automatisch..."
    if [ "$PKG_MGR" = "apt" ]; then
        run_as_root apt-get update -qq
        run_as_root apt-get install -y python3 python3-venv python3-pip
    elif [ "$PKG_MGR" = "dnf" ]; then
        run_as_root dnf install -y python3 python3-pip
    elif [ "$PKG_MGR" = "yum" ]; then
        run_as_root yum install -y python3 python3-pip
    else
        err "Kann Python 3 nicht automatisch installieren.\nBitte installiere Python 3.8+ manuell: https://www.python.org/downloads/"
    fi
fi

# Versionscheck
PYOK=$(python3 -c "import sys; print(sys.version_info >= (3,8))" 2>/dev/null || echo "False")
[ "$PYOK" = "True" ] || err "Python 3.8 oder neuer wird benoetigt. Aktuell: $(python3 --version)"
ok "Python $(python3 --version | cut -d' ' -f2)"

# ── python3-venv sicherstellen ─────────────────────────────────────────────────
info "Pruefe python3-venv..."
if ! python3 -m venv --help >/dev/null 2>&1; then
    echo "  python3-venv fehlt. Installiere es jetzt..."
    if [ "$PKG_MGR" = "apt" ]; then
        run_as_root apt-get install -y python3-venv
    elif [ "$PKG_MGR" = "dnf" ]; then
        run_as_root dnf install -y python3
    elif [ "$PKG_MGR" = "yum" ]; then
        run_as_root yum install -y python3
    else
        err "Bitte installiere python3-venv manuell:\n  sudo apt install python3-venv"
    fi
fi
ok "python3-venv verfuegbar"

# ── curl sicherstellen ─────────────────────────────────────────────────────────
info "Pruefe curl..."
if ! command -v curl >/dev/null 2>&1; then
    echo "  curl fehlt. Installiere es jetzt..."
    if [ "$PKG_MGR" = "apt" ]; then
        run_as_root apt-get install -y curl
    elif [ "$PKG_MGR" = "dnf" ]; then
        run_as_root dnf install -y curl
    elif [ "$PKG_MGR" = "yum" ]; then
        run_as_root yum install -y curl
    else
        err "Bitte installiere curl manuell."
    fi
fi
ok "curl verfuegbar"

echo ""

# ── Bestehendes Verzeichnis ────────────────────────────────────────────────────
if [ -d "$INSTALL_DIR" ]; then
    echo "  Hinweis: Das Verzeichnis './$INSTALL_DIR' existiert bereits."
    ask "Aktualisieren (bestehende Daten bleiben erhalten)? [J/n]" ow
    ow="${ow:-J}"
    [[ "$ow" =~ ^[JjYy] ]] || { echo "  Abgebrochen."; exit 0; }
fi

# ── Download ───────────────────────────────────────────────────────────────────
info "Lade TeamRally Server herunter..."
curl -fsSL "$BASE_URL/$TARBALL" -o "$TARBALL" \
    || err "Download fehlgeschlagen. Bitte Internetverbindung pruefen."
ok "Download abgeschlossen"

# ── Entpacken ─────────────────────────────────────────────────────────────────
info "Entpacke nach ./$INSTALL_DIR/ ..."
mkdir -p "$INSTALL_DIR"
tar -xzf "$TARBALL" -C "$INSTALL_DIR"
rm "$TARBALL"
cd "$INSTALL_DIR"
ok "Entpackt"

# ── Python-Umgebung ────────────────────────────────────────────────────────────
info "Erstelle Python-Umgebung (nur einmalig, dauert einen Moment)..."
python3 -m venv .venv
source .venv/bin/activate
pip install -q --upgrade pip
pip install -q -r requirements.txt
ok "Python-Umgebung bereit"

chmod +x start_server.sh

# ── Server-IP ermitteln fuer Abschlusshinweis ──────────────────────────────────
MY_IP=$(hostname -I 2>/dev/null | awk '{print $1}' || echo "DEINE-SERVER-IP")

echo ""
echo "============================================="
echo "   Installation abgeschlossen!"
echo ""
echo "   Naechster Schritt:"
echo "     cd $INSTALL_DIR && ./start_server.sh"
echo ""
echo "   Der Browser-Assistent oeffnet sich dann"
echo "   automatisch unter:"
echo "     http://$MY_IP:5000/admin/"
echo ""
echo "   Stelle sicher, dass Port 5000 in der"
echo "   Firewall deines Hosters freigegeben ist."
echo "============================================="
echo ""
ask "Server jetzt starten? [J/n]" answer
answer="${answer:-J}"
if [[ "$answer" =~ ^[JjYy] ]]; then
    ./start_server.sh
fi
