#!/usr/bin/env bash
# Thin per-room wrapper around RuView's OWN provision.py
# (https://github.com/ruvnet/ruview, firmware/esp32-csi-node/provision.py) — this
# repo does not reimplement RuView's provisioning, it just fills in this stack's
# own Wi-Fi/MQTT settings so you don't have to retype them per room. See
# README.md for why RuView's actual CSI firmware is integrated, not forked.
#
# Usage: ./provision-room.sh <room-name> <serial-port> [extra provision.py args]
# Example: ./provision-room.sh living-room /dev/ttyUSB0

set -euo pipefail

ROOM="${1:?Usage: ./provision-room.sh <room-name> <serial-port> [extra args]}"
PORT="${2:?Usage: ./provision-room.sh <room-name> <serial-port> [extra args]}"
shift 2

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="$SCRIPT_DIR/rooms.env"
if [[ ! -f "$ENV_FILE" ]]; then
  echo "Missing $ENV_FILE — cp rooms.env.example rooms.env and fill it in first." >&2
  exit 1
fi
# shellcheck disable=SC1090
source "$ENV_FILE"

: "${RUVIEW_REPO_DIR:?rooms.env is missing RUVIEW_REPO_DIR}"
: "${WIFI_SSID:?rooms.env is missing WIFI_SSID}"
: "${WIFI_PASSWORD:?rooms.env is missing WIFI_PASSWORD}"
: "${MQTT_BROKER_HOST:?rooms.env is missing MQTT_BROKER_HOST}"

PROVISION_PY="$RUVIEW_REPO_DIR/firmware/esp32-csi-node/provision.py"
if [[ ! -f "$PROVISION_PY" ]]; then
  echo "Error: $PROVISION_PY not found." >&2
  echo "  RUVIEW_REPO_DIR ($RUVIEW_REPO_DIR) doesn't look like a real RuView checkout —" >&2
  echo "  clone https://github.com/ruvnet/ruview there first, per its own README." >&2
  exit 1
fi

echo "--- Provisioning RuView node for room '$ROOM' on $PORT ---"
echo "(Only --port/--ssid/--password/--mqtt below are confirmed against RuView's own"
echo " README — if you need MQTT auth or a specific node-name flag, check"
echo " 'python3 $PROVISION_PY --help' against YOUR checked-out version and pass it as"
echo " an extra argument to this script; nothing here guesses flag names it hasn't"
echo " confirmed. See README.md's 'Manual verification still outstanding'.)"
echo

python3 "$PROVISION_PY" \
  --port "$PORT" \
  --ssid "$WIFI_SSID" \
  --password "$WIFI_PASSWORD" \
  --mqtt "$MQTT_BROKER_HOST" \
  "$@"
