#!/usr/bin/env bash
# Join a LiveKit conversation from the Pi.
#
# Calls the local Pi UI's /api/join endpoint, which itself asks the scheduler
# for a short-lived LiveKit access token. The script prints the meet URL
# AND (if --open) opens it in the default browser on the Pi.
#
# Usage:
#   ./join_convo.sh
#   ./join_convo.sh --room robopark-pi-test --identity alice --open
#   PI_UI=http://192.168.1.159:8081 ./join_convo.sh --open

set -euo pipefail

PI_UI="${PI_UI:-http://127.0.0.1:8081}"
ROOM="${ROOM:-robopark-pi-test}"
IDENTITY="${IDENTITY:-}"
OPEN=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --room) ROOM="$2"; shift 2 ;;
    --identity) IDENTITY="$2"; shift 2 ;;
    --open) OPEN=1; shift ;;
    --pi-ui) PI_UI="$2"; shift 2 ;;
    -h|--help)
      sed -n '2,12p' "$0"; exit 0 ;;
    *) echo "unknown arg: $1" >&2; exit 1 ;;
  esac
done

BODY=$(jq -nc --arg room "$ROOM" --arg identity "$IDENTITY" \
  '{room:$room, identity:$identity}')

echo "Requesting token from $PI_UI (room=$ROOM identity=$IDENTITY)..."
RESP=$(curl -fsS -X POST "$PI_UI/api/join" \
  -H 'Content-Type: application/json' -d "$BODY")

URL=$(echo "$RESP" | jq -r '
  "https://meet.livekit.io/custom?livekitUrl=" + (.url | @uri) +
  "&token=" + (.token | @uri)
')

EXPIRES=$(echo "$RESP" | jq -r '.expires_at')
echo "Token expires: $EXPIRES"
echo "Meet URL:"
echo "  $URL"

if [[ $OPEN -eq 1 ]]; then
  if command -v xdg-open >/dev/null 2>&1; then xdg-open "$URL" >/dev/null 2>&1 || true
  elif command -v sensible-browser >/dev/null 2>&1; then sensible-browser "$URL" >/dev/null 2>&1 || true
  elif command -v open >/dev/null 2>&1; then open "$URL" >/dev/null 2>&1 || true
  else echo "no browser opener found; copy the URL above" >&2; exit 2; fi
  echo "(opened in browser)"
fi