#!/usr/bin/bash
#
# console/query-remote.sh — install conman client and connect to a console
# on pfv-tsys4 over Tailscale.
#
# Usage:
#   bash console/query-remote.sh                    # list consoles
#   bash console/query-remote.sh pfv-r5-core-01      # connect to a console
#
set -euo pipefail

REMOTE_HOST="${REMOTE_HOST:-pfv-tsys4}"
REMOTE_PORT="${REMOTE_PORT:-7890}"

echo "============================================"
echo "  Conman Remote Console Access"
echo "  Server: ${REMOTE_HOST}:${REMOTE_PORT} (Tailscale)"
echo "============================================"

# --- 1. Install conman client if missing ---
if ! command -v conman >/dev/null 2>&1; then
  echo ""
  echo "--- Installing conman client ---"
  if sudo -n true 2>/dev/null; then
    sudo apt-get update -qq && sudo apt-get install -y -qq conman
  else
    echo "  Passwordless sudo not available. Please run:"
    echo "    sudo apt-get update && sudo apt-get install -y conman"
    echo "  Then re-run this script."
    exit 1
  fi
else
  echo "  conman client already installed."
fi

# --- 2. Verify connectivity ---
echo ""
echo "--- Connectivity check ---"
if timeout 3 bash -c "echo > /dev/tcp/${REMOTE_HOST}/${REMOTE_PORT}" 2>/dev/null; then
  echo "  [OK] ${REMOTE_HOST}:${REMOTE_PORT} reachable"
else
  echo "  [FAIL] Cannot reach ${REMOTE_HOST}:${REMOTE_PORT}"
  echo "  Is Tailscale up? Is conmand running on ${REMOTE_HOST}?"
  exit 1
fi

# --- 3. List or connect ---
CONSOLE="${1:-}"
if [ -z "$CONSOLE" ]; then
  echo ""
  echo "--- Available consoles ---"
  conman -d "${REMOTE_HOST}:${REMOTE_PORT}" -q
  echo ""
  echo "To connect: bash $0 <console-name>"
  echo "  e.g: bash $0 pfv-r5-core-01"
else
  echo ""
  echo "--- Connecting to: $CONSOLE ---"
  echo "  Escape sequence: &. (to disconnect)"
  echo ""
  conman -d "${REMOTE_HOST}:${REMOTE_PORT}" -f "$CONSOLE"
fi
