#!/usr/bin/env bash
# Apply nginx fix for ERR_TOO_MANY_REDIRECTS (X-Forwarded-Proto) and /snap/ on VMID 5000.
# Run from Proxmox host that has VMID 5000, or set EXPLORER_VM_HOST=root@<node-ip> to run via SSH.
# After running, reload nginx inside the VM so the new config is active.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
EXPLORER_MONOREPO="$(cd "$SCRIPT_DIR/.." && pwd)"

VMID="${EXPLORER_VMID:-5000}"
EXPLORER_NODE="${EXPLORER_VM_HOST:-}"
if [[ -n "$EXPLORER_NODE" && "$EXPLORER_NODE" == *"@"* ]]; then
  SSH_TARGET="$EXPLORER_NODE"
else
  SSH_TARGET="root@${EXPLORER_NODE:-192.168.11.12}"
fi

# If we're not on the Proxmox host (no pct), copy script to host, push into VM, and run inside VM
if ! command -v pct &>/dev/null || ! pct list 2>/dev/null | grep -q "^$VMID "; then
  if [[ -n "${EXPLORER_VM_HOST:-}" ]]; then
    echo "Running on Proxmox node via SSH: $SSH_TARGET (applying fix inside VMID $VMID)"
    scp -o StrictHostKeyChecking=no -o ConnectTimeout=10 \
      "$SCRIPT_DIR/fix-nginx-serve-custom-frontend.sh" \
      "$SSH_TARGET:/tmp/fix-nginx-explorer.sh" 2>/dev/null || true
    ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 "$SSH_TARGET" \
      "pct push $VMID /tmp/fix-nginx-explorer.sh /tmp/fix-nginx-explorer.sh --perms 0755 && pct exec $VMID -- bash /tmp/fix-nginx-explorer.sh"
    exit $?
  else
    echo "Run this on the Proxmox host that has VMID $VMID, or set EXPLORER_VM_HOST=root@<node-ip>"
    exit 1
  fi
fi

echo "=============================================="
echo "Apply nginx explorer fix (VMID $VMID)"
echo "=============================================="
echo ""

# Copy the fix script into the VM and run it (prefer custom frontend config with /snap/ and X-Forwarded-Proto)
FIX_SCRIPT="$SCRIPT_DIR/fix-nginx-serve-custom-frontend.sh"
if [[ ! -f "$FIX_SCRIPT" ]]; then
  echo "Missing $FIX_SCRIPT"
  exit 1
fi

pct push "$VMID" "$FIX_SCRIPT" /tmp/fix-nginx-serve-custom-frontend.sh
pct exec "$VMID" -- bash /tmp/fix-nginx-serve-custom-frontend.sh

echo ""
echo "Done. Verify: curl -sI https://explorer.d-bis.org/snap/ (expect 200, no redirect loop)."
