#!/usr/bin/env bash
# Smoke-test live cast API (public join + authenticated list).
#
#   ./scripts/test_live_cast_api.sh
#   COOKIE='ac_crash_sess=…' CRASH_BASE=https://apps.f0xx.org/app/androidcast_project/crashes ./scripts/test_live_cast_api.sh
set -euo pipefail

CRASH_BASE="${CRASH_BASE:-http://127.0.0.1:8080/app/androidcast_project/crashes}"
API_URL="${CRASH_BASE}/api/live_cast.php"
COOKIE_JAR="${TMPDIR:-/tmp}/live_cast_cookies_$$.txt"
trap 'rm -f "$COOKIE_JAR"' EXIT

CURL_AUTH=()
if [[ -n "${COOKIE:-}" ]]; then
  CURL_AUTH=(-H "Cookie: ${COOKIE}")
else
  user="${CRASH_USER:-admin}"
  pass="${CRASH_PASS:-admin}"
  curl -sS -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X POST \
    -d "username=${user}&password=${pass}" \
    "${CRASH_BASE}/login" -o /dev/null
  CURL_AUTH=(-b "$COOKIE_JAR")
fi

sid="smoke-live-$(date +%s)"
echo "POST create_intent (${sid})"
create_code="$(curl -sS -o /tmp/live_create.json -w '%{http_code}' \
  "${CURL_AUTH[@]}" \
  -H 'Content-Type: application/json' \
  -d "{\"action\":\"create_intent\",\"platform\":\"android\",\"device_id\":\"smoke-device\",\"max_duration_s\":120}" \
  "${API_URL}")"
echo "create HTTP ${create_code}"
cat /tmp/live_create.json
echo

session_id="$(python3 - <<'PY'
import json
try:
    d=json.load(open("/tmp/live_create.json"))
    print(d.get("session",{}).get("session_id",""))
except Exception:
    print("")
PY
)"
if [[ -z "${session_id}" ]]; then
  echo "FAIL: no session_id in create response" >&2
  exit 1
fi

echo "GET public session"
pub_code="$(curl -sS -o /tmp/live_session.json -w '%{http_code}' \
  "${API_URL}?action=session&session_id=${session_id}")"
echo "session HTTP ${pub_code}"
head -c 300 /tmp/live_session.json
echo

echo "POST public join_event"
join_code="$(curl -sS -o /tmp/live_join.json -w '%{http_code}' \
  -H 'Content-Type: application/json' \
  -d "{\"action\":\"join_event\",\"session_id\":\"${session_id}\",\"event_type\":\"open\",\"platform\":\"chrome\"}" \
  "${API_URL}")"
echo "join HTTP ${join_code}"
cat /tmp/live_join.json
echo

echo "GET list (auth)"
list_code="$(curl -sS -o /tmp/live_list.json -w '%{http_code}' \
  "${CURL_AUTH[@]}" \
  "${API_URL}?action=list&days=7")"
echo "list HTTP ${list_code}"
head -c 300 /tmp/live_list.json
echo

for code in "${create_code}" "${pub_code}" "${join_code}" "${list_code}"; do
  if [[ "${code}" != "200" ]]; then
    echo "FAIL: expected HTTP 200" >&2
    exit 1
  fi
done
echo "OK"
