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

# ==========================================================
# GamePiZero Installer / Updater
# Raspberry Pi OS Lite / Headless
# ==========================================================

APP_NAME="gamepizero"

ZIP_URL="https://git.exystem.net/miho/gamepizero-dist/raw/branch/main/GamePiZero.zip"

INSTALL_DIR="/opt/gamepizero"
TMP_DIR="/tmp/gamepizero-install"

EXECUTABLE_PATH="/opt/gamepizero/GamePiZero.App"

SERVICE_NAME="gamepizero.service"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}"

REBOOT_REQUIRED=0

# ==========================================================
# Prüfung
# ==========================================================

if [[ "${EUID}" -ne 0 ]]; then
  echo "Bitte mit sudo ausführen:"
  echo "  sudo ./gamepizero.sh install"
  echo "  sudo ./gamepizero.sh update"
  exit 1
fi

ACTION="${1:-}"

case "${ACTION}" in
  install|update)
    ;;
  *)
    echo "Verwendung:"
    echo "  sudo ./gamepizero.sh install"
    echo "  sudo ./gamepizero.sh update"
    exit 1
    ;;
esac

# ==========================================================
# Funktionen
# ==========================================================

log() {
  echo "[INFO] $1"
}

error() {
  echo "[ERROR] $1" >&2
}

install_dependencies() {
  log "Installiere benötigte Pakete..."

  apt-get update
  apt-get install -y curl unzip raspi-config
}

enable_i2c() {
  log "Prüfe I²C..."

  if command -v raspi-config >/dev/null 2>&1; then
    if raspi-config nonint get_i2c | grep -q "0"; then
      log "I²C ist bereits aktiviert."
    else
      log "Aktiviere I²C..."
      raspi-config nonint do_i2c 0
      REBOOT_REQUIRED=1
    fi
  else
    error "raspi-config nicht gefunden. I²C konnte nicht automatisch aktiviert werden."
  fi
}

stop_service_if_exists() {
  if systemctl list-unit-files | grep -q "^${SERVICE_NAME}"; then
    log "Stoppe bestehenden Dienst..."
    systemctl stop "${SERVICE_NAME}" || true
  fi
}

download_zip() {
  log "Lade Anwendung herunter..."

  rm -rf "${TMP_DIR}"
  mkdir -p "${TMP_DIR}"

  curl -fL "${ZIP_URL}" -o "${TMP_DIR}/${APP_NAME}.zip"
}

extract_app() {
  log "Installiere Anwendung nach ${INSTALL_DIR}..."

  mkdir -p "${INSTALL_DIR}"
  unzip -o "${TMP_DIR}/${APP_NAME}.zip" -d "${INSTALL_DIR}"

  if [[ ! -f "${EXECUTABLE_PATH}" ]]; then
    error "Executable wurde nicht gefunden:"
    error "${EXECUTABLE_PATH}"
    exit 1
  fi

  chmod +x "${EXECUTABLE_PATH}"

  # App läuft als root, daher Dateien root:root
  chown -R root:root "${INSTALL_DIR}"

  rm -rf "${TMP_DIR}"
}

install_service() {
  log "Erstelle systemd-Dienst..."

  cat > "${SERVICE_FILE}" <<EOF
[Unit]
Description=GamePiZero
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
WorkingDirectory=${INSTALL_DIR}
ExecStart=${EXECUTABLE_PATH}
Restart=always
RestartSec=5

# Die App läuft bewusst als root
User=root
Group=root

Environment=DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1

[Install]
WantedBy=multi-user.target
EOF

  systemctl daemon-reload
  systemctl enable "${SERVICE_NAME}"
  systemctl restart "${SERVICE_NAME}"
}

show_status() {
  log "Dienststatus:"
  systemctl --no-pager status "${SERVICE_NAME}" || true
}

# ==========================================================
# Ablauf
# ==========================================================

log "Aktion: ${ACTION}"

install_dependencies
enable_i2c

if [[ "${ACTION}" == "update" ]]; then
  stop_service_if_exists
fi

download_zip
extract_app
install_service
show_status

echo
echo "Fertig."

if [[ "${REBOOT_REQUIRED}" == "1" ]]; then
  echo
  echo "I²C wurde aktiviert."
  echo "Ein Reboot ist empfohlen:"
  echo "  sudo reboot"
fi