#!/bin/bash
# lxc_hook_cleanup.sh — hook de nettoyage des montages dynamiques après arrêt LXC

LOGFILE="/tmp/lxc_hook_cleanup.log"
BIND_CONFIG="/opt/scripts_local/bind_dynamic_mount.conf"

echo "[HOOK DEBUG] Hook triggered for $1 $2 at $(date)" >> "$LOGFILE"

VMID="$1"
PHASE="$2"

# On n'agit que lors du post-stop
if [[ "$PHASE" != "post-stop" ]]; then
  exit 0
fi

CONF_FILE="/etc/pve/lxc/${VMID}.conf"

if [[ ! -f "$CONF_FILE" ]]; then
  echo "[HOOK ERROR] Conf file not found for VM $VMID" >> "$LOGFILE"
  exit 1
fi

# Extraire tous les mpX actuels
ALL_MOUNTS=$(grep -E '^mp[0-9]+:' "$CONF_FILE" | cut -d: -f1)

# Extraire ceux qui sont définis dans le fichier de config
STATIC_MOUNTS=$(awk -F'|' -v vm="$VMID" '$1 == vm { print }' "$BIND_CONFIG" | while read -r _ _ dst; do
  grep -E "mp[0-9]+:.*mp=$dst" "$CONF_FILE" | cut -d: -f1
done)

# Supprimer tous les mpX non présents dans STATIC_MOUNTS
for mp in $ALL_MOUNTS; do
  if ! echo "$STATIC_MOUNTS" | grep -q "^$mp$"; then
    echo "[HOOK CLEANUP] Removing $mp from VM $VMID" >> "$LOGFILE"
    pct set "$VMID" -delete "$mp" >> "$LOGFILE" 2>&1
  fi
done

echo "[HOOK DONE] Cleanup finished for VM $VMID" >> "$LOGFILE"
exit 0