#!/usr/bin/env bash
# Auvi Live Stream — RTSP ingest via ffmpeg
#
# Captures one still from an RTSP (or HTTP) camera every N seconds and POSTs it
# to the public Auvi ingest endpoint. No storage, no dependencies beyond
# ffmpeg + curl. Run it under systemd/supervisor so it restarts on reboot.
#
#   AUVI_ENDPOINT="https://your-app.lovable.app/api/public/ingest/riverside-north" \
#   AUVI_KEY="auvi_xxx" \
#   RTSP_URL="rtsp://user:pass@10.0.0.42:554/stream1" \
#   ./auvi-rtsp-ingest.sh
#
# Optional:
#   AUVI_INTERVAL   seconds between frames (default 10)
#   AUVI_AUTH       header | bearer | basic | query   (default header)
#   RTSP_TRANSPORT  tcp | udp                         (default tcp)
#   JPEG_QUALITY    ffmpeg -q:v, 2 (best) .. 31       (default 3)

set -uo pipefail

ENDPOINT="${AUVI_ENDPOINT:?set AUVI_ENDPOINT to your camera ingest URL}"
KEY="${AUVI_KEY:?set AUVI_KEY to the camera device key}"
RTSP="${RTSP_URL:?set RTSP_URL to your camera stream}"
INTERVAL="${AUVI_INTERVAL:-10}"
AUTH="${AUVI_AUTH:-header}"
TRANSPORT="${RTSP_TRANSPORT:-tcp}"
QUALITY="${JPEG_QUALITY:-3}"

FRAME="$(mktemp -t auvi-frame-XXXXXX.jpg)"
trap 'rm -f "$FRAME"' EXIT

url="$ENDPOINT"
auth_args=(-H "x-device-key: $KEY")
case "$AUTH" in
  header) ;;
  bearer) auth_args=(-H "authorization: Bearer $KEY") ;;
  basic)  auth_args=(--user "auvi:$KEY") ;;
  query)  auth_args=(); url="${ENDPOINT}?key=${KEY}" ;;
  *) echo "unknown AUVI_AUTH: $AUTH (header|bearer|basic|query)" >&2; exit 1 ;;
esac

echo "auvi: verifying key against $ENDPOINT"
curl -sf "${auth_args[@]}" "$url" || { echo "auvi: key check failed" >&2; exit 1; }
echo

while true; do
  started=$(date +%s)
  captured_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)

  if ffmpeg -hide_banner -loglevel error -y \
      -rtsp_transport "$TRANSPORT" -i "$RTSP" \
      -frames:v 1 -q:v "$QUALITY" -f image2 "$FRAME"; then

    code=$(curl -s -o /tmp/auvi-response.json -w '%{http_code}' \
      -X POST "$url" \
      "${auth_args[@]}" \
      -H "content-type: image/jpeg" \
      -H "x-captured-at: $captured_at" \
      --max-time 30 \
      --data-binary "@$FRAME")

    case "$code" in
      200|201) echo "$(date -u +%H:%M:%S) ok $(wc -c <"$FRAME") bytes" ;;
      429)     echo "$(date -u +%H:%M:%S) rate limited — backing off"; sleep 5 ;;
      *)       echo "$(date -u +%H:%M:%S) upload failed ($code): $(cat /tmp/auvi-response.json)" >&2 ;;
    esac
  else
    echo "$(date -u +%H:%M:%S) capture failed — camera unreachable?" >&2
  fi

  elapsed=$(( $(date +%s) - started ))
  remaining=$(( INTERVAL - elapsed ))
  (( remaining > 0 )) && sleep "$remaining"
done
