#!/usr/bin/env bash
#
# setup-ha-nut.sh — Add the Home Assistant NUT integration via REST API.
#
# Idempotent: skips if a NUT entry already exists. Reads secrets from
# ~/.config/pfvcluster/ (ha-token, nut-password) or env vars.
#
# Usage:
#   bash ups/setup-ha-nut.sh
#
# Env overrides:
#   HA_TOKEN     HA long-lived access token
#   NUT_PASS     NUT upsd password for the homeassistant user
#   HA_HOST      HA host (default pfv-bms.knel.net)
#   NUT_HOST     upsd host (default 192.168.3.11 — LAN, see README)
#   NUT_PORT     upsd port (default 3493)
#   NUT_USER     upsd user (default homeassistant)
#   NUT_UPS      UPS name (default apc-smartups-c1500)
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONF_DIR="${PFV_CONF_DIR:-$HOME/.config/pfvcluster}"

# --- HA token ---
HA_TOKEN="${HA_TOKEN:-}"
if [[ -z "$HA_TOKEN" ]]; then
  TOKEN_FILE="$CONF_DIR/ha-token"
  if [[ -f "$TOKEN_FILE" ]]; then
    HA_TOKEN="$(head -1 "$TOKEN_FILE" | tr -d '[:space:]')"
  else
    echo "error: no HA token. Set \$HA_TOKEN or create $TOKEN_FILE" >&2
    echo "  (HA → Profile → Long-Lived Access Tokens → Create Token)" >&2
    exit 1
  fi
fi

# --- NUT password ---
NUT_PASS="${NUT_PASS:-}"
if [[ -z "$NUT_PASS" ]]; then
  PASS_FILE="$CONF_DIR/nut-password"
  if [[ -f "$PASS_FILE" ]]; then
    NUT_PASS="$(head -1 "$PASS_FILE" | tr -d '[:space:]')"
  else
    echo "error: no NUT password. Set \$NUT_PASS or create $PASS_FILE" >&2
    echo "  (value is in /etc/nut/upsd.users on the NUT host)" >&2
    exit 1
  fi
fi

# --- connection params (override for your own kit) ---
export HA_TOKEN
export NUT_PASS
export HA_HOST="${HA_HOST:-pfv-bms.knel.net}"
export HA_PORT="${HA_PORT:-8123}"
export NUT_HOST="${NUT_HOST:-192.168.3.11}"
export NUT_PORT="${NUT_PORT:-3493}"
export NUT_USER="${NUT_USER:-homeassistant}"
export NUT_UPS="${NUT_UPS:-apc-smartups-c1500}"

echo "HA:   ${HA_HOST}:${HA_PORT}"
echo "NUT:  ${NUT_USER}@${NUT_HOST}:${NUT_PORT} (UPS: ${NUT_UPS})"
echo ""

exec python3 "$SCRIPT_DIR/ha-nut-setup.py"
