#!/usr/bin/bash
#
# powerman/query-remote.sh — install powerman client locally and query
# the Cyclades PDU running on pfv-tsys1 over Tailscale.
#
set -euo pipefail

REMOTE_HOST="${REMOTE_HOST:-pfv-tsys1}"
REMOTE_PORT="${REMOTE_PORT:-10101}"

echo "============================================"
echo "  Powerman Remote PDU Query"
echo "  Server: ${REMOTE_HOST}:${REMOTE_PORT} (Tailscale)"
echo "============================================"

# --- 1. Install powerman client if missing ---
if ! command -v powerman >/dev/null 2>&1; then
  echo ""
  echo "--- Installing powerman client ---"
  if sudo -n true 2>/dev/null; then
    sudo apt-get update -qq && sudo apt-get install -y -qq powerman
  else
    echo "  Passwordless sudo not available. Please run this command in a terminal:"
    echo ""
    echo "    sudo apt-get update && sudo apt-get install -y powerman"
    echo ""
    echo "  Then re-run this script."
    exit 1
  fi
else
  echo "  powerman 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 powermand running on ${REMOTE_HOST}?"
  exit 1
fi

export POWERMAN_SERVER="${REMOTE_HOST}:${REMOTE_PORT}"

# --- 3. List outlets ---
echo ""
echo "--- Outlets ---"
powerman -h "${REMOTE_HOST}:${REMOTE_PORT}" -l

# --- 4. Query status ---
echo ""
echo "--- Status ---"
powerman -h "${REMOTE_HOST}:${REMOTE_PORT}" -q

echo ""
echo "============================================"
echo "  Done."
echo ""
echo "  To control an outlet from this workstation:"
echo "    powerman -h ${REMOTE_HOST}:${REMOTE_PORT} -0 outlet-10  # off"
echo "    powerman -h ${REMOTE_HOST}:${REMOTE_PORT} -1 outlet-10  # on"
echo "    powerman -h ${REMOTE_HOST}:${REMOTE_PORT} -c outlet-10  # cycle"
echo "============================================"
