#!/bin/bash
set -e

# --- VARIABLES A VERIFIER ---
HOST_IP="192.168.244.23"
NETMASK="255.255.255.0"
GATEWAY="192.168.244.1"
DNS="213.186.33.99"

echo "=== DEBUT CONFIGURATION (Mode Sécurisé) ==="

# 1. RECUPERATION UUIDs (Filtrage strict sur VLAN -1)
HOST_UUID=$(xe host-list --minimal)
PIF_ETH0=$(xe pif-list device=eth0 VLAN=-1 host-uuid=$HOST_UUID --minimal)
PIF_ETH1=$(xe pif-list device=eth1 VLAN=-1 host-uuid=$HOST_UUID --minimal)
PIF_ETH2=$(xe pif-list device=eth2 VLAN=-1 host-uuid=$HOST_UUID --minimal)
PIF_ETH3=$(xe pif-list device=eth3 VLAN=-1 host-uuid=$HOST_UUID --minimal)

echo "UUID eth0 physique : $PIF_ETH0"

# 2. CREATION BOND 0
echo "-- Creation Bond 0 (LACP) --"
NET_BOND0=$(xe network-create name-label="Bond0 Network")
xe bond-create network-uuid=$NET_BOND0 pif-uuids=$PIF_ETH0,$PIF_ETH1 mode=lacp
echo "Attente synchronisation XAPI (5s)..."
sleep 5
PIF_BOND0=$(xe pif-list network-uuid=$NET_BOND0 host-uuid=$HOST_UUID --minimal)
echo "Bond0 OK : $PIF_BOND0"

# 3. CREATION BOND 1
echo "-- Creation Bond 1 (LACP) --"
NET_BOND1=$(xe network-create name-label="Bond1 Network")
xe bond-create network-uuid=$NET_BOND1 pif-uuids=$PIF_ETH2,$PIF_ETH3 mode=lacp
sleep 2
PIF_BOND1=$(xe pif-list network-uuid=$NET_BOND1 host-uuid=$HOST_UUID --minimal)
echo "Bond1 OK : $PIF_BOND1"

# 4. CREATION VLAN MGMT (1069)
echo "-- Creation VLAN 1069 (MGMT) --"
NET_MGMT=$(xe network-create name-label="VLAN 1069 - MGMT")
xe vlan-create pif-uuid=$PIF_BOND0 vlan=1069 network-uuid=$NET_MGMT
sleep 2
PIF_MGMT=$(xe pif-list network-uuid=$NET_MGMT host-uuid=$HOST_UUID --minimal)

# --- SECURITE CRITIQUE ---
if [ -z "$PIF_MGMT" ]; then
    echo "ERREUR CRITIQUE : Le PIF du VLAN 1069 n'a pas été créé correctement."
    echo "ARRET DU SCRIPT AVANT LA COUPURE RESEAU."
    echo "Votre accès actuel sur eth0 est toujours valide."
    exit 1
fi
echo "Vérification OK : PIF VLAN MGMT trouvé ($PIF_MGMT)"
# -------------------------

# 5. CREATION AUTRES VLANS
echo "-- Creation autres VLANs --"
xe vlan-create pif-uuid=$PIF_BOND0 vlan=1070 network-uuid=$(xe network-create name-label="VLAN 1070 - USER")
xe vlan-create pif-uuid=$PIF_BOND1 vlan=1071 network-uuid=$(xe network-create name-label="VLAN 1071 - CEPH")
xe vlan-create pif-uuid=$PIF_BOND1 vlan=1072 network-uuid=$(xe network-create name-label="VLAN 1072 - DATA")

# 6. BASCULE
echo "-- Configuration IP Statique sur VLAN 1069 --"
xe pif-reconfigure-ip uuid=$PIF_MGMT mode=static IP=$HOST_IP netmask=$NETMASK gateway=$GATEWAY DNS=$DNS

echo "!!! ATTENTION !!!"
echo "Je vais basculer l'interface de management maintenant."
echo "La connexion SSH/IPMI actuelle VA COUPER."
echo "Si le LAG OVH est actif, le serveur répondra sur $HOST_IP (VLAN 1069) dans quelques secondes."
sleep 3

xe host-management-reconfigure pif-uuid=$PIF_MGMT

echo "=== SUCCES (Normalement) ==="
