#!/usr/bin/env bash
# Apply nginx config for explorer + /snap/ on VMID 5000 from the Proxmox host (or via SSH).
# Runs fix-nginx-serve-custom-frontend.sh inside the VM so /snap and /snap/ return 200.
# Usage: ./apply-nginx-snap-vmid5000.sh

set -euo pipefail

VMID=5000
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FIX_SCRIPT="$SCRIPT_DIR/fix-nginx-serve-custom-frontend.sh"
PROXMOX_HOST="${PROXMOX_HOST_R630_02:-192.168.11.12}"

if [ ! -f "$FIX_SCRIPT" ]; then
  echo "❌ Fix script not found: $FIX_SCRIPT"
  exit 1
fi

echo "=========================================="
echo "Apply nginx (explorer + /snap/) on VMID $VMID"
echo "=========================================="
echo ""

if [ -f "/proc/1/cgroup" ] && grep -q "lxc" /proc/1/cgroup 2>/dev/null; then
  echo "Running inside VMID $VMID – executing fix script directly"
  bash "$FIX_SCRIPT"
elif command -v pct &>/dev/null; then
  echo "Running from Proxmox host – executing fix script inside VM via pct"
  pct exec $VMID -- bash -s < "$FIX_SCRIPT"
else
  echo "Running from remote – pushing script and executing via SSH + pct"
  TMP_SCRIPT="/tmp/fix-nginx-snap-$$.sh"
  scp -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$FIX_SCRIPT" root@"${PROXMOX_HOST}:$TMP_SCRIPT"
  ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no root@"${PROXMOX_HOST}" "pct exec $VMID -- bash -s < $TMP_SCRIPT; rm -f $TMP_SCRIPT"
fi

echo ""
echo "✅ Nginx config applied. /snap and /snap/ should return 200."
echo "Verify: curl -sS -o /dev/null -w '%{http_code}' https://explorer.d-bis.org/snap/"
echo ""
