#!/bin/bash
# setup_bind_mount.sh — Installe bind_dynamic_mount avec hook & systemd
set -euo pipefail

SELF_DIR="$(cd "$(dirname "$0")" && pwd)"
SCRIPT_DIR="/opt/scripts_local"
SCRIPT_NAME="bind_dynamic_mount.sh"
HOOK_NAME="lxc_hook_cleanup.sh"
CONFIG_NAME="bind_dynamic_mount.conf"
SNIPPET_DIR="/var/lib/vz/snippets"
SERVICE_NAME="bind-dynamic-mount"

mkdir -p "$SCRIPT_DIR"
mkdir -p "$SNIPPET_DIR"

# Copy main script
install -m 755 "$SELF_DIR/$SCRIPT_NAME" "$SCRIPT_DIR/$SCRIPT_NAME"

# Copy config if missing
if [[ ! -f "$SCRIPT_DIR/$CONFIG_NAME" ]]; then
  cat <<EOF > "$SCRIPT_DIR/$CONFIG_NAME"
# VMID|SRC_PATH|DEST_PATH
10007|/lxc_shares/backup|/media/backup
10007|/lxc_shares/scripts|/opt/scripts_remote
EOF
  echo "✅ Exemple de config créée: $SCRIPT_DIR/$CONFIG_NAME"
fi

# Copy hook script
install -m 755 "$SELF_DIR/$HOOK_NAME" "$SNIPPET_DIR/$HOOK_NAME"
echo "✅ Hook installé: $SNIPPET_DIR/$HOOK_NAME"

# Auto-configure hookscript for all VMs listed in config
awk -F '|' '{print $1}' "$SCRIPT_DIR/$CONFIG_NAME" | sort -u | while read -r vmid; do
  conf="/etc/pve/lxc/${vmid}.conf"
  if [[ -f "$conf" ]] && ! grep -q "^hookscript: local:snippets/$HOOK_NAME" "$conf"; then
    echo "🔧 Ajout du hook à VM $vmid"
    pct set "$vmid" -hookscript "local:snippets/$HOOK_NAME"
  fi
done

# Install systemd service
cat <<EOF > "/etc/systemd/system/${SERVICE_NAME}.service"
[Unit]
Description=Bind LXC mounts dynamically
After=network.target

[Service]
Type=oneshot
ExecStart=$SCRIPT_DIR/$SCRIPT_NAME

[Install]
WantedBy=multi-user.target
EOF

# Install systemd timer
cat <<EOF > "/etc/systemd/system/${SERVICE_NAME}.timer"
[Unit]
Description=Run bind-dynamic-mount every 1 minute

[Timer]
OnBootSec=30
OnUnitActiveSec=60
Persistent=true

[Install]
WantedBy=timers.target
EOF

systemctl daemon-reexec
systemctl daemon-reload
systemctl enable --now ${SERVICE_NAME}.timer

echo "✅ Timer activé: systemctl status ${SERVICE_NAME}.timer"