#!/usr/bin/env bash
# ---------------------------------------------------------------------------
#  Pterodactyl Panel Manager – backup, update & restore utility
#  Author: <votre-nom-ou-société>
#  Version: 1.5  (2025-06-19)
# ---------------------------------------------------------------------------
#  Description :
#    • Sauvegarde votre installation Pterodactyl Panel.
#    • Installe les dépendances manquantes (PHP 8.3, MariaDB, Nginx, Redis…).
#    • Met à jour le panel en suivant la méthode officielle (release panel.tar.gz).
#    • Restaure une sauvegarde existante.
#
#  Compatibilité : Debian 11/12, Ubuntu 22.04, Rocky 9 (root requis, bash ≥ 4).
# ---------------------------------------------------------------------------
set -euo pipefail
IFS=$'\n\t'

# ------------------------- CONFIGURATION PAR DÉFAUT -------------------------
BACKUP_DIR="/var/backups/pterodactyl"
PANEL_DIR="/var/www/pterodactyl"   # Unique chemin utilisé
WEB_USER="www-data"                # Adaptez si nginx, apache, etc.
REQUIRED_CMDS=(curl tar php composer git redis-server mysqld nginx)

# ----------------------------- COULEURS & UI --------------------------------
red()    { printf "\e[31m%s\e[0m\n" "$*"; }
green()  { printf "\e[32m%s\e[0m\n" "$*"; }
yellow() { printf "\e[33m%s\e[0m\n" "$*"; }
info()   { printf "\n\e[34m[INFO]\e[0m  %s\n" "$*"; }
warn()   { printf "\n\e[33m[WARN]\e[0m  %s\n" "$*"; }
error()  { printf "\n\e[31m[ERREUR]\e[0m %s\n" "$*"; }

pause()  { read -rp $'Appuyez sur Entrée pour continuer…'; }

# ----------------------- INSTALLATION DÉPENDANCES ---------------------------
detect_pkg_manager() {
  command -v apt-get &>/dev/null && { echo apt; return; }
  command -v dnf &>/dev/null     && { echo dnf; return; }
  command -v yum &>/dev/null     && { echo yum; return; }
  error "Aucun gestionnaire de paquets compatible trouvé. Installez manuellement les dépendances."
  exit 1
}

install_dependencies() {
  local missing=()
  for cmd in "${REQUIRED_CMDS[@]}"; do command -v "$cmd" &>/dev/null || missing+=("$cmd"); done
  (( ${#missing[@]} == 0 )) && { green "Toutes les dépendances sont déjà installées."; return; }

  yellow "Dépendances manquantes : ${missing[*]}"
  read -rp "Installer automatiquement ? (O/n) : " yn
  [[ "$yn" =~ ^[Nn]$ ]] && { error "Installation annulée."; exit 1; }

  local pm=$(detect_pkg_manager)
  info "Installation via $pm…"

  case $pm in
    apt)
      apt-get update -y
      apt-get install -y lsb-release apt-transport-https ca-certificates wget curl gnupg2 software-properties-common
      # PHP Sury repo
      curl -sSLo /usr/share/keyrings/deb.sury.org-php.gpg https://packages.sury.org/php/apt.gpg
      echo "deb [signed-by=/usr/share/keyrings/deb.sury.org-php.gpg] https://packages.sury.org/php/ $(lsb_release -sc) main" >/etc/apt/sources.list.d/php.list
      # Redis repo
      curl -fsSL https://packages.redis.io/gpg | gpg --dearmor -o /usr/share/keyrings/redis.gpg
      echo "deb [signed-by=/usr/share/keyrings/redis.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" >/etc/apt/sources.list.d/redis.list
      apt-get update -y
      apt-get install -y php8.3 php8.3-{common,cli,gd,mysql,mbstring,bcmath,xml,fpm,curl,zip} mariadb-server nginx tar unzip git redis-server composer
      ;;
    dnf)
      dnf install -y epel-release
      dnf module reset -y php && dnf module enable -y php:8.3
      dnf install -y php php-cli php-common php-gd php-mysqlnd php-mbstring php-bcmath php-xml php-fpm php-curl php-zip mariadb-server nginx tar unzip git redis composer
      ;;
    yum)
      yum install -y epel-release yum-utils
      yum-config-manager --enable remi-php83
      yum install -y php php-cli php-common php-gd php-mysqlnd php-mbstring php-bcmath php-xml php-fpm php-curl php-zip mariadb-server nginx tar unzip git redis composer
      ;;
  esac

  green "Installation des dépendances terminée."
}

# -------------------------- SAUVEGARDE & RESTORE ----------------------------
backup_panel() {
  [[ -d "$PANEL_DIR" ]] || { error "Le répertoire $PANEL_DIR n'existe pas."; exit 1; }
  mkdir -p "$BACKUP_DIR"
  local ts=$(date +"%Y-%m-%d_%H-%M-%S")
  local file="$BACKUP_DIR/panel_${ts}.tar.gz"
  info "Sauvegarde dans $file…"
  tar -czf "$file" -C "$PANEL_DIR" .
  green "Sauvegarde terminée."
}

restore_panel() {
  local backups=( $(ls -1t "$BACKUP_DIR"/panel_*.tar.gz 2>/dev/null) )
  (( ${#backups[@]} )) || { error "Aucune sauvegarde trouvée."; return; }
  yellow "Sauvegardes disponibles :"
  select file in "${backups[@]}"; do [[ -n "$file" ]] && break; done

  warn "Cette opération écrasera $PANEL_DIR."
  read -rp "Confirmer la restauration ? (oui/N) : " confirm
  [[ "$confirm" == "oui" ]] || { info "Opération annulée."; return; }

  php "$PANEL_DIR/artisan" down || true
  rm -rf "$PANEL_DIR"/*
  tar -xzf "$file" -C "$PANEL_DIR"
  chown -R "$WEB_USER":"$WEB_USER" "$PANEL_DIR"
  php "$PANEL_DIR/artisan" up || true
  green "Restauration effectuée."
}

# ------------------------------ UPDATE --------------------------------------
update_panel() {
  install_dependencies
  backup_panel
  cd "$PANEL_DIR"

  yellow "Mise en maintenance…"
  php artisan down || true

  info "Téléchargement de la dernière release…"
  curl -L https://github.com/pterodactyl/panel/releases/latest/download/panel.tar.gz | tar -xzv

  chmod -R 755 storage/* bootstrap/cache
  composer install --no-dev --optimize-autoloader --quiet
  php artisan view:clear
  php artisan config:clear
  php artisan migrate --seed --force
  chown -R "$WEB_USER":"$WEB_USER" "$PANEL_DIR"/*
  php artisan queue:restart
  php artisan up
  green "Mise à jour terminée !"
}

# ----------------------------- MENU & EXEC ----------------------------------
main_menu() {
  PS3=$'\nChoisissez une option : '
  yellow "======== Pterodactyl Panel Manager ========"
  select opt in "Mettre à jour le panel" "Restaurer une sauvegarde" "Quitter"; do
    case $REPLY in
      1) update_panel ;;
      2) restore_panel ;;
      3) break ;;
      *) echo "Option invalide" ;;
    esac
    pause
    clear
    yellow "======== Pterodactyl Panel Manager ========"
  done
}

[[ $EUID -ne 0 ]] && { error "Exécutez ce script en root ou avec sudo."; exit 1; }
[[ ! -d "$PANEL_DIR" ]] && { error "Le répertoire $PANEL_DIR n'existe pas."; exit 1; }
mkdir -p "$BACKUP_DIR"
main_menu
