#!/usr/bin/env bash
# Shared SSH/SCP helpers for Proxmox pct deploy from dev-bis-ali (LAN).
set -euo pipefail

OMNL_PVE_HOST="${OMNL_PVE_HOST:-192.168.11.13}"
OMNL_PVE_USER="${OMNL_PVE_USER:-root}"
OMNL_PVE_SSH_HOST="${OMNL_PVE_SSH_HOST:-${OMNL_PVE_HOST}}"
OMNL_PVE_SSH_TARGET="${OMNL_PVE_USER}@${OMNL_PVE_SSH_HOST}"

# Avoid cloudflared ProxyJump when using raw 192.168.11.x from dev-bis-ali.
OMNL_PVE_SSH_BASE_OPTS=(
  -o BatchMode=yes
  -o ConnectTimeout=20
  -o StrictHostKeyChecking=accept-new
  -o ProxyJump=none
)

OMNL_PVE_SSH_PREFIX=()

omnl_pve_detect_sudo() {
  if [[ -n "${OMNL_PVE_SSH_PREFIX[*]:-}" ]]; then
    return 0
  fi
  if [[ "${OMNL_PVE_USE_SUDO:-auto}" == "0" ]]; then
    OMNL_PVE_SSH_PREFIX=()
    return 0
  fi
  if [[ "${OMNL_PVE_USE_SUDO:-auto}" == "1" ]]; then
    OMNL_PVE_SSH_PREFIX=(sudo)
    return 0
  fi
  if ssh "${OMNL_PVE_SSH_BASE_OPTS[@]}" "$OMNL_PVE_SSH_TARGET" true 2>/dev/null; then
    OMNL_PVE_SSH_PREFIX=()
  elif sudo -n ssh "${OMNL_PVE_SSH_BASE_OPTS[@]}" "$OMNL_PVE_SSH_TARGET" true 2>/dev/null; then
    OMNL_PVE_SSH_PREFIX=(sudo)
  else
    echo "Cannot SSH to ${OMNL_PVE_SSH_TARGET} (tried direct and sudo)." >&2
    echo "Fix: bash scripts/deployment/setup-dev1-pve-ssh-access.sh" >&2
    return 1
  fi
}

omnl_pve_ssh() {
  omnl_pve_detect_sudo
  "${OMNL_PVE_SSH_PREFIX[@]}" ssh "${OMNL_PVE_SSH_BASE_OPTS[@]}" "$OMNL_PVE_SSH_TARGET" "$@"
}

omnl_pve_scp() {
  omnl_pve_detect_sudo
  "${OMNL_PVE_SSH_PREFIX[@]}" scp "${OMNL_PVE_SSH_BASE_OPTS[@]}" "$@"
}

omnl_pve_preflight() {
  omnl_pve_detect_sudo
  omnl_pve_ssh "command -v pct >/dev/null && pct list >/dev/null" || {
    echo "Proxmox pct unavailable on ${OMNL_PVE_SSH_TARGET}" >&2
    return 1
  }
}

omnl_pve_ensure_ct_running() {
  local ctid="$1"
  local status
  status="$(omnl_pve_ssh "pct status ${ctid} 2>/dev/null || true")"
  if [[ -z "$status" ]]; then
    echo "CT ${ctid} does not exist on ${OMNL_PVE_SSH_TARGET} — skip" >&2
    return 1
  fi
  if [[ "$status" == *"status: running"* ]]; then
    return 0
  fi
  if [[ "$status" == *"status: stopped"* ]]; then
    log_msg "Starting stopped CT ${ctid}..."
    omnl_pve_ssh "pct start ${ctid}"
    sleep 3
    return 0
  fi
  echo "CT ${ctid} is not runnable (${status})" >&2
  return 1
}

log_msg() { echo "[$(date -Iseconds)] $*" >&2; }
