#!/usr/bin/env bash
# Ensure dev1@dev-bis-ali can reach Proxmox via sudo ssh (LAN, no cloudflared).
set -euo pipefail

CONFIG="${HOME}/.ssh/config.d-ecosystem"
PUB="${HOME}/.ssh/id_ed25519.pub"

log() { echo "[$(date -Iseconds)] $*"; }

if [[ ! -f "$PUB" ]]; then
  echo "Missing $PUB — generate or copy operator SSH key first." >&2
  exit 1
fi

if [[ -f "$CONFIG" ]] && grep -q 'Host 192.168.11\.\*' "$CONFIG"; then
  log "Patching $CONFIG — disable ProxyJump for LAN 192.168.11.* (use pve-r630-* aliases from laptop via -J dev-bis)"
  tmp="$(mktemp)"
  awk '
    /^Host 192\.168\.11\.\*/ { inblock=1 }
    inblock && /^[[:space:]]+ProxyJump dev-bis/ { sub(/ProxyJump dev-bis/, "ProxyJump none"); }
    { print }
    inblock && /^$/ { inblock=0 }
  ' "$CONFIG" > "$tmp"
  mv "$tmp" "$CONFIG"
  chmod 600 "$CONFIG"
fi

log "Testing Proxmox SSH (direct, then sudo)..."
# shellcheck source=lib/omnl-pve-ssh.sh
source "$(dirname "$0")/lib/omnl-pve-ssh.sh"
omnl_pve_preflight
log "Proxmox SSH OK via ${OMNL_PVE_SSH_PREFIX[*]:-direct} → ${OMNL_PVE_SSH_TARGET}"
