#!/usr/bin/env bash
# Clusev host CLI — short wrappers around the production stack.
# Generated by install.sh (it substitutes __CLUSEV_DIR__ with the install directory) and
# installed to /usr/local/bin/clusev. Operators run `clusev <command>` from anywhere instead
# of long `docker compose -f docker-compose.prod.yml ...` invocations. The compose filename is
# referenced internally only — it is never printed to the operator.
set -euo pipefail

# __CLUSEV_DIR__ is replaced by install.sh with a printf %q shell-escaped path, so this
# unquoted assignment stays injection-safe even if the install path contains shell syntax.
CLUSEV_DIR=__CLUSEV_DIR__
COMPOSE_FILE="${CLUSEV_DIR}/docker-compose.prod.yml"

compose() { docker compose -f "$COMPOSE_FILE" "$@"; }

usage() {
  cat <<'EOF'
clusev — Fleet-Control Verwaltung (Host)

  sudo clusev update     Update holen, Image neu bauen, Migrationen anwenden (root)
  clusev reset-admin     Admin-Zugang zuruecksetzen (2FA entfernen, Passwort neu setzen)
  clusev unban <ip>      Gebannte IP entsperren (--all fuer alle)
  clusev restart         Stack neu starten
  clusev logs [dienst]   Logs folgen (Strg-C beendet)
  clusev ps              Dienst-Status (Alias: status)
  clusev migrate         Datenbank-Migrationen anwenden
  clusev artisan <...>   beliebiges artisan-Kommando im app-Container
  clusev version         installierte Version anzeigen
  clusev help            diese Uebersicht

Was im Hintergrund laeuft:
  update      -> update.sh (git pull + Image-Rebuild + migrate)
  reset-admin -> docker compose exec app php artisan clusev:reset-admin
  migrate     -> docker compose exec app php artisan migrate --force
EOF
}

cmd="${1:-help}"; shift 2>/dev/null || true
case "$cmd" in
  update)         exec "${CLUSEV_DIR}/update.sh" "$@" ;;
  reset-admin)    compose exec app php artisan clusev:reset-admin "$@" ;;
  unban)          compose exec app php artisan clusev:unban "$@" ;;
  restart)        compose up -d "$@" ;;
  logs)           compose logs -f "$@" ;;
  ps|status)      compose ps "$@" ;;
  migrate)        compose exec app php artisan migrate --force "$@" ;;
  artisan)        compose exec app php artisan "$@" ;;
  version)        grep -oE "'version' => '[^']+'" "${CLUSEV_DIR}/config/clusev.php" \
                    | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -n1 || true ;;
  help|-h|--help) usage ;;
  *)              printf 'Unbekannter Befehl: %s\n\n' "$cmd" >&2; usage; exit 64 ;;
esac
