#!/bin/bash
# bind_dynamic_mount.sh — Monte dynamiquement les shares dans les LXC une fois disponibles
set -euo pipefail

CONFIG_FILE="$(dirname "$0")/bind_dynamic_mount.conf"
HOOKSCRIPT="local:snippets/lxc_hook_cleanup.sh"
SCRIPT_NAME="$(basename "$0")"
MARKER_BASE="/etc/pve/lxc"

FORCE=false
DEBUG=false

# Parsing arguments
for arg in "$@"; do
  [[ "$arg" == "--force" ]] && FORCE=true
  [[ "$arg" == "--debug" ]] && DEBUG=true
done

log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $SCRIPT_NAME: $1"
}

get_next_mpx_index() {
  local vmid="$1"
  local conf="$MARKER_BASE/$vmid.conf"
  local i=0
  while grep -q "^mp$i:" "$conf"; do
    ((i++))
  done
  echo "$i"
}

already_mounted() {
  local vmid="$1" dst="$2"
  grep -q ",mp=$dst" "$MARKER_BASE/$vmid.conf" && return 0 || return 1
}

mount_failed_list=()

while IFS='|' read -r VMID SRC DST || [[ -n "$VMID" ]]; do
  [[ -z "$VMID" || "$VMID" =~ ^# ]] && continue

  log "🔍 VM=$VMID | SRC=$SRC | DST=$DST"
  CONF="$MARKER_BASE/$VMID.conf"

  if ! pct status "$VMID" &>/dev/null; then
    log "⚠️ VM $VMID does not exist, skipping."
    continue
  fi

  if ! pct status "$VMID" | grep -q running; then
    log "⚠️ VM $VMID is not running, skipping."
    continue
  fi

  if [[ ! -d "$SRC" ]]; then
    log "❌ Source path $SRC does not exist."
    mount_failed_list+=("$VMID: $SRC → $DST (source missing)")
    continue
  fi

  if already_mounted "$VMID" "$DST"; then
    if [[ "$FORCE" == true ]]; then
      log "⚠️ Mount $DST exists, replacing due to --force"
      # Let hookscript clean it, we simply remount here
    else
      log "✅ Already mounted: $DST in $VMID"
      continue
    fi
  fi

  IDX=$(get_next_mpx_index "$VMID")
  MOUNT_OPT="$SRC,mp=$DST"
  log "🔗 pct set $VMID -mp$IDX "$MOUNT_OPT""
  if pct set "$VMID" -mp${IDX} "$MOUNT_OPT" >> /dev/null 2>&1; then
    log "✅ Mounted: $SRC → $DST (mp$IDX)"
  else
    log "❌ Failed to mount $SRC → $DST"
    mount_failed_list+=("$VMID: $SRC → $DST (pct set failed)")
    continue
  fi

  # Ajout automatique du hookscript si absent
  if ! grep -q "^hookscript: $HOOKSCRIPT" "$CONF"; then
    log "🔧 Adding hookscript to VM $VMID"
    pct set "$VMID" -hookscript "$HOOKSCRIPT" || log "⚠️ Failed to set hookscript on VM $VMID"
  fi

done < "$CONFIG_FILE"

if [[ ${#mount_failed_list[@]} -gt 0 ]]; then
  log "📣 Summary of failed mounts:"
  for err in "${mount_failed_list[@]}"; do
    log "  - $err"
  done
else
  log "✅ All mounts completed successfully."
fi