#!/bin/bash
###############################################################################
# Module 01 - Configuration PVE
# - Support Proxmox 8 (Bookworm, format .list) ET Proxmox 9 (Trixie, deb822)
# - Désactive le repo enterprise
# - Active le repo no-subscription
# - Supprime le nag de subscription
# - Met à jour le système
# - Configure le hostname et l'IP du PVE
# - Installe quelques outils utiles
###############################################################################

set -euo pipefail

log() { echo -e "\033[0;34m[$(date +%H:%M:%S)]\033[0m $*"; }
ok()  { echo -e "\033[0;32m[OK]\033[0m $*"; }
err() { echo -e "\033[0;31m[ERROR]\033[0m $*"; }
warn(){ echo -e "\033[1;33m[WARN]\033[0m $*"; }

# ----------------------------------------------------------------------------
# Détection version Debian (Bookworm = PVE 8, Trixie = PVE 9)
# ----------------------------------------------------------------------------
DEBIAN_CODENAME=$(. /etc/os-release && echo "$VERSION_CODENAME")
log "Debian codename détecté : ${DEBIAN_CODENAME}"

# ----------------------------------------------------------------------------
# Repos APT - Désactiver les repos enterprise
# ----------------------------------------------------------------------------
log "Configuration des repos APT..."

# --- Format ancien (.list) - Proxmox 8 et avant ---
for repo_file in pve-enterprise.list ceph.list; do
    if [[ -f "/etc/apt/sources.list.d/${repo_file}" ]]; then
        sed -i 's/^deb/#deb/' "/etc/apt/sources.list.d/${repo_file}"
        ok "Repo ${repo_file} désactivé (format .list)"
    fi
done

# --- Format DEB822 (.sources) - Proxmox 9 ---
for sources_file in pve-enterprise.sources ceph.sources; do
    if [[ -f "/etc/apt/sources.list.d/${sources_file}" ]]; then
        # On désactive en mettant Enabled: false
        if grep -q "^Enabled:" "/etc/apt/sources.list.d/${sources_file}"; then
            sed -i 's/^Enabled:.*/Enabled: false/' "/etc/apt/sources.list.d/${sources_file}"
        else
            echo "Enabled: false" >> "/etc/apt/sources.list.d/${sources_file}"
        fi
        ok "Repo ${sources_file} désactivé (format deb822)"
    fi
done

# ----------------------------------------------------------------------------
# Activer le repo no-subscription (format adapté à la version)
# ----------------------------------------------------------------------------
# Détection du format à utiliser : si on a déjà des .sources, on reste en deb822
if ls /etc/apt/sources.list.d/*.sources >/dev/null 2>&1; then
    # Format DEB822 (Proxmox 9)
    if [[ ! -f /etc/apt/sources.list.d/pve-no-subscription.sources ]]; then
        cat > /etc/apt/sources.list.d/pve-no-subscription.sources <<EOF
Types: deb
URIs: http://download.proxmox.com/debian/pve
Suites: ${DEBIAN_CODENAME}
Components: pve-no-subscription
Signed-By: /usr/share/keyrings/proxmox-archive-keyring.gpg
EOF
        ok "Repo no-subscription ajouté (deb822, ${DEBIAN_CODENAME})"
    fi
else
    # Format classique .list (Proxmox 8)
    if [[ ! -f /etc/apt/sources.list.d/pve-no-subscription.list ]]; then
        cat > /etc/apt/sources.list.d/pve-no-subscription.list <<EOF
deb http://download.proxmox.com/debian/pve ${DEBIAN_CODENAME} pve-no-subscription
EOF
        ok "Repo no-subscription ajouté (.list, ${DEBIAN_CODENAME})"
    fi
fi

# ----------------------------------------------------------------------------
# Suppression du nag de subscription
# ----------------------------------------------------------------------------
log "Suppression du nag de subscription..."
NAG_FILE="/usr/share/javascript/proxmox-widget-toolkit/proxmoxlib.js"
if [[ -f "$NAG_FILE" ]]; then
    sed -i.bak "s/data\.status\s*!==\s*['\"]Active['\"]/false/g" "$NAG_FILE" || true
    ok "Nag de subscription désactivé"
fi

# ----------------------------------------------------------------------------
# Mise à jour système
# ----------------------------------------------------------------------------
log "Mise à jour des paquets (ceci peut prendre quelques minutes)..."
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get dist-upgrade -y -qq \
    -o Dpkg::Options::="--force-confdef" \
    -o Dpkg::Options::="--force-confold"
ok "Système à jour"

# ----------------------------------------------------------------------------
# Installation d'outils utiles
# ----------------------------------------------------------------------------
log "Installation d'outils utiles..."
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq \
    curl wget vim htop tmux iperf3 net-tools dnsutils python3 \
    >/dev/null
ok "Outils installés"

# ----------------------------------------------------------------------------
# Configuration de l'IP du PVE
# ----------------------------------------------------------------------------
log "Configuration de l'IP du PVE vers ${PVE_IP}/24..."

PVE_BRIDGE="vmbr0"

# Backup
cp /etc/network/interfaces "/etc/network/interfaces.bak-$(date +%Y%m%d-%H%M%S)"

# Modification via python pour fiabilité
python3 <<PYEOF
import re

new_ip = "${PVE_IP}"
gateway = "${GATEWAY}"
bridge = "${PVE_BRIDGE}"

with open('/etc/network/interfaces', 'r') as f:
    content = f.read()

pattern = rf'(iface\s+{bridge}\s+inet\s+static\s*\n)(.*?)(?=\n(?:iface|auto|source|\Z))'
match = re.search(pattern, content, re.DOTALL)

if match:
    block_start = match.group(1)
    block_body = match.group(2)
    block_body = re.sub(r'(\s+address\s+)[\d./]+', rf'\g<1>{new_ip}/24', block_body)
    block_body = re.sub(r'(\s+gateway\s+)[\d.]+', rf'\g<1>{gateway}', block_body)
    new_block = block_start + block_body
    content = content[:match.start()] + new_block + content[match.end():]
    with open('/etc/network/interfaces', 'w') as f:
        f.write(content)
    print("Interface modifiée avec succès")
else:
    print("ERREUR: Bridge vmbr0 non trouvé dans /etc/network/interfaces")
    exit(1)
PYEOF

ok "IP PVE configurée à ${PVE_IP}/24 (gateway ${GATEWAY})"

# ----------------------------------------------------------------------------
# Configuration DNS
# ----------------------------------------------------------------------------
log "Configuration DNS..."
cat > /etc/resolv.conf <<EOF
nameserver 1.1.1.1
nameserver 8.8.8.8
EOF
ok "DNS configuré (1.1.1.1, 8.8.8.8)"

# ----------------------------------------------------------------------------
# Téléchargement du template Debian pour les CT
# ----------------------------------------------------------------------------
log "Mise à jour de la liste des templates LXC..."
pveam update >/dev/null 2>&1 || true

# Sur Trixie (PVE 9) on peut utiliser debian-13, sur Bookworm (PVE 8) debian-12
# On prend le plus récent dispo pour la version Debian courante
DEBIAN_TEMPLATE=$(pveam available --section system 2>/dev/null | grep -E "debian-(12|13)-standard" | awk '{print $2}' | sort -V | tail -1)

if [[ -z "$DEBIAN_TEMPLATE" ]]; then
    err "Aucun template Debian trouvé"
    exit 1
fi

log "Template Debian sélectionné : ${DEBIAN_TEMPLATE}"

if ! pveam list "$TEMPLATE_STORAGE" 2>/dev/null | grep -q "$DEBIAN_TEMPLATE"; then
    log "Téléchargement..."
    pveam download "$TEMPLATE_STORAGE" "$DEBIAN_TEMPLATE"
    ok "Template ${DEBIAN_TEMPLATE} téléchargé"
else
    ok "Template ${DEBIAN_TEMPLATE} déjà présent"
fi

# Export pour les modules suivants
echo "$DEBIAN_TEMPLATE" > /tmp/ng-debian-template
echo "${TEMPLATE_STORAGE}:vztmpl/${DEBIAN_TEMPLATE}" > /tmp/ng-debian-template-path

ok "Module 01 (PVE config) terminé"
echo
echo "⚠️  L'IP du PVE sera ${PVE_IP} après reboot du PVE."
echo "⚠️  Pour l'instant, on continue avec la session actuelle."
echo