#!/bin/bash
# ============================================================
#  REBOOTLY ARCHIVES — 01 — Création Template LXC Debian 12
#
#  Pré-installe dans le template :
#  - Docker CE + images pré-pullées (mariadb, manticore,
#    memcached, piler, portainer, debian:bookworm-slim)
#  - Node.js 22
#  - Nginx, Python3, Openssl
#  - pst-utils (readpst — import Outlook PST)
#  - vim, htop, jq, net-tools, dnsutils
#  - DNS forcé (resolv.conf)
#
#  Le déploiement client clone ce template (~2 min, pas internet)
#  À lancer UNE SEULE FOIS sur le nœud Proxmox.
# ============================================================
set -euo pipefail
exec > >(tee /var/log/rebootly-create-lxc-template.log) 2>&1

GREEN='\033[0;32m'; CYAN='\033[0;36m'; YELLOW='\033[1;33m'
RED='\033[0;31m'; BOLD='\033[1m'; NC='\033[0m'
ok()      { echo -e "${GREEN}[✓]${NC} $1"; }
section() { echo -e "\n${CYAN}${BOLD}┌─ $1${NC}"; }
warn()    { echo -e "${YELLOW}[!]${NC} $1"; }
err()     { echo -e "${RED}[✗]${NC} $1"; exit 1; }
info()    { echo -e "    ${CYAN}→${NC} $1"; }

TEMPLATE_ID="${REBOOTLY_TEMPLATE_ID:-9000}"
CT_STORAGE="${REBOOTLY_STORAGE:-local}"
YES="${REBOOTLY_YES:-false}"  # true = non-interactif (--yes)
CT_TEMPLATE="local:vztmpl/debian-12-standard_12.12-1_amd64.tar.zst"
CT_DNS="1.1.1.1 8.8.8.8"
TEMP_IP="10.10.0.250/24"
TEMP_GW="10.10.0.1"
TEMP_BRIDGE="vmbr1"

clear
echo -e "${CYAN}${BOLD}"
echo "  ┌─────────────────────────────────────────────────────┐"
echo "  │   Rebootly Archives — Création Template LXC         │"
echo "  │   Docker + Node.js 22 + Nginx + pst-utils + images  │"
echo "  └─────────────────────────────────────────────────────┘"
echo -e "${NC}"
echo -e "  Template ID : ${BOLD}$TEMPLATE_ID${NC}"
echo -e "  Stockage    : ${BOLD}$CT_STORAGE${NC}"
echo -e "  Durée       : 10-20 min (pull images Docker)"
echo ""
warn "Lance UNE SEULE FOIS — le déploiement client clonera ce template."
if [[ "$YES" != "true" ]]; then
  read -p "  Continuer ? [o/N] " -n 1 -r; echo
  [[ ! $REPLY =~ ^[oO]$ ]] && echo "Annulé." && exit 0
else
  echo "  [AUTO] Mode non-interactif — confirmation automatique"
fi

# ═══════════════════════════════════════════════════════════════
section "0/6 — Prérequis"
[[ $EUID -ne 0 ]]           && err "Root requis"
command -v pct >/dev/null 2>&1 || err "pct introuvable — Proxmox VE requis"

# Template CT disponible ?
CT_TMPL_FILE=$(echo "$CT_TEMPLATE" | sed 's|local:vztmpl/||')
if ! pveam list local 2>/dev/null | grep -q "$CT_TMPL_FILE"; then
  warn "Template CT absent — téléchargement..."
  pveam update >/dev/null 2>&1 || true
  pveam download local "$CT_TMPL_FILE" || err "Téléchargement template CT échoué"
fi
ok "Template CT présent"

# Template LXC déjà existant ?
if pct status "$TEMPLATE_ID" >/dev/null 2>&1; then
  warn "Template LXC $TEMPLATE_ID existe déjà."
  if [[ "$YES" != "true" ]]; then
    read -p "  Supprimer et recréer ? [o/N] " -n 1 -r; echo
    [[ $REPLY =~ ^[oO]$ ]] || { echo "Annulé."; exit 0; }
  else
    echo "  [AUTO] Suppression ancien template..."
  fi
  pct stop "$TEMPLATE_ID" 2>/dev/null || true
  sleep 3
  pct destroy "$TEMPLATE_ID" && ok "Ancien template supprimé"
fi
ok "Prérequis OK"

# ═══════════════════════════════════════════════════════════════
section "1/6 — Création LXC temporaire $TEMPLATE_ID"
pct create "$TEMPLATE_ID" "$CT_TEMPLATE" \
  --hostname  "rebootly-template" \
  --rootfs    "${CT_STORAGE}:8" \
  --memory    2048 \
  --cores     2 \
  --net0      "name=eth0,bridge=${TEMP_BRIDGE},ip=${TEMP_IP},gw=${TEMP_GW}" \
  --nameserver  "$CT_DNS" \
  --searchdomain "local" \
  --unprivileged 1 \
  --features  "nesting=1,keyctl=1,mknod=1" \
  --start 0

pct start "$TEMPLATE_ID"
info "Attente démarrage LXC (20s)..."
sleep 20
ok "LXC $TEMPLATE_ID démarré"

# ═══════════════════════════════════════════════════════════════
section "2/6 — DNS + Paquets système"
pct exec "$TEMPLATE_ID" -- bash -c "
  # Fix DNS Debian 12 (resolv.conf symlink systemd-resolved)
  rm -f /etc/resolv.conf
  echo -e 'nameserver 1.1.1.1\nnameserver 8.8.8.8' > /etc/resolv.conf
  # Test réseau
  for i in 1 2 3 4 5; do
    ping -c1 -W2 1.1.1.1 >/dev/null 2>&1 && echo 'Réseau OK' && break
    echo \"Attente réseau [\$i/5]...\"; sleep 5
  done
  ping -c1 -W3 1.1.1.1 >/dev/null 2>&1 || { echo 'ERREUR: pas de réseau !'; exit 1; }
  # Forcer IPv4 pour apt
  echo 'Acquire::ForceIPv4 \"true\";' > /etc/apt/apt.conf.d/99force-ipv4
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -qq
  apt-get install -y -qq \
    curl wget ca-certificates gnupg lsb-release \
    nginx python3 openssl \
    apt-transport-https software-properties-common \
    cron net-tools dnsutils \
    pst-utils \
    vim htop jq
  echo 'Paquets OK'
  readpst -V 2>/dev/null | head -1 || echo 'readpst installé'
"
ok "Paquets système installés"

# ═══════════════════════════════════════════════════════════════
section "3/6 — Docker CE"
pct exec "$TEMPLATE_ID" -- bash -c "
  install -m 0755 -d /etc/apt/keyrings
  curl -fsSL https://download.docker.com/linux/debian/gpg \
    | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
  chmod a+r /etc/apt/keyrings/docker.gpg
  echo \"deb [arch=\$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
    https://download.docker.com/linux/debian \$(lsb_release -cs) stable\" \
    > /etc/apt/sources.list.d/docker.list
  apt-get update -qq
  apt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-compose-plugin
  systemctl enable docker && systemctl start docker
  docker --version
"
ok "Docker CE installé"

# ═══════════════════════════════════════════════════════════════
section "4/6 — Node.js 22"
pct exec "$TEMPLATE_ID" -- bash -c "
  curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
  apt-get install -y -qq nodejs
  node --version && npm --version
"
ok "Node.js 22 installé"

# ═══════════════════════════════════════════════════════════════
section "5/6 — Pré-pull images Docker depuis registry privé"
REGISTRY="registry.rebootly.cloud"
REGISTRY_USER="rebootly"
REGISTRY_PASS="jupfvS2dFDvL2fOXYB0RwDiX"
info "Login registry privé ${REGISTRY}..."
pct exec "$TEMPLATE_ID" -- bash -c "
  echo '${REGISTRY_PASS}' | docker login '${REGISTRY}' -u '${REGISTRY_USER}' --password-stdin && echo 'Login OK'
"
info "Pull des images depuis ${REGISTRY} (peut prendre 5-10 min)..."
pct exec "$TEMPLATE_ID" -- bash -c "
  REGISTRY='${REGISTRY}'
  # Pull depuis registry privé — fallback Docker Hub si indispo
  IMAGES=(
    'rb-piler:1.4.8|sutoj/piler:1.4.8'
    'rb-mariadb:10.11|mariadb:10.11'
    'rb-manticore:6.3.4|manticoresearch/manticore:6.3.4'
    'rb-memcached:alpine|memcached:alpine'
    'rb-portainer:latest|portainer/portainer-ce:latest'
  )
  for entry in \"\${IMAGES[@]}\"; do
    reg_tag=\"\${entry%%|*}\"
    hub_tag=\"\${entry##*|}\"
    reg_image=\"\${REGISTRY}/\${reg_tag}\"
    echo -n \"  Pull \${reg_tag}... \"
    if docker pull \"\${reg_image}\" >/dev/null 2>&1; then
      docker tag \"\${reg_image}\" \"\${hub_tag}\" 2>/dev/null || true
      echo \"[registry OK]\"
    else
      echo \"[registry indispo — Docker Hub fallback]\"
      docker pull \"\${hub_tag}\" >/dev/null 2>&1 && echo \"  [Hub OK]\" || echo \"  [ERREUR]\"
    fi
  done
  docker images --format 'table {{.Repository}}\t{{.Tag}}\t{{.Size}}'
  echo 'Images pré-pullées OK'
"
ok "Images Docker pré-pullées"

# ═══════════════════════════════════════════════════════════════
section "6/6 — Nettoyage + conversion en template"
pct exec "$TEMPLATE_ID" -- bash -c "
  # Désactiver exim4 + postfix (libérer port 25 pour Mailpiler)
  systemctl stop    exim4   2>/dev/null || true
  systemctl disable exim4   2>/dev/null || true
  systemctl mask    exim4   2>/dev/null || true
  systemctl stop    postfix 2>/dev/null || true
  systemctl disable postfix 2>/dev/null || true
  systemctl mask    postfix 2>/dev/null || true
  # Créer répertoires de base
  mkdir -p /opt/rebootly /var/www/rebootly
  # Nettoyer apt
  apt-get clean
  apt-get autoremove -y 2>/dev/null || true
  rm -rf /var/cache/apt/archives/*
  # Reset machine-id pour que les clones aient un ID unique
  truncate -s 0 /etc/machine-id
  rm -f /var/lib/dbus/machine-id 2>/dev/null || true
  echo 'Nettoyage OK'
"
ok "Nettoyage effectué"

info "Arrêt du LXC..."
pct stop "$TEMPLATE_ID"
sleep 5

info "Conversion en template..."
pct template "$TEMPLATE_ID"
ok "LXC $TEMPLATE_ID → template ✓"

# ── Résumé ────────────────────────────────────────────────────
echo ""
echo -e "${CYAN}${BOLD}╔══════════════════════════════════════════════════════════════╗"
echo -e "║      Template LXC Rebootly créé avec succès !              ║"
echo -e "╠══════════════════════════════════════════════════════════════╣"
printf  "║  %-14s : %-45s║\n" "Template ID"  "$TEMPLATE_ID"
printf  "║  %-14s : %-45s║\n" "Contenu"      "Docker + Node22 + Nginx + pst-utils"
printf  "║  %-14s : %-45s║\n" "Déploiement"  "Clone = ~2 min, zéro internet"
echo -e "╠══════════════════════════════════════════════════════════════╣"
echo -e "║  Déployer un client :                                       ║"
echo -e "║  bash /root/rebootly-archives/02-deploy-client.sh          ║"
echo -e "╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo "  Log : /var/log/rebootly-create-lxc-template.log"
echo ""
