#!/usr/bin/env bash
# vdo-ninja-setup.sh — self-host VDO.Ninja (open-source WebRTC) so old phones become
# realtime wireless mics over Wi-Fi/Tailscale.
#
# VDO.Ninja is a STATIC web app (no npm/node needed). We clone it once and serve it
# over HTTPS (phones only allow the mic on HTTPS) using the phone-mic self-signed cert.
# Note: peers still find each other through VDO.Ninja's public handshake server,
# so the Mac and phones need internet. Audio itself flows peer-to-peer.
#
#   ./vdo-ninja-setup.sh install   # once (git clone, ~100 MB — use Wi-Fi)
#   ./vdo-ninja-setup.sh start     # serves https://<mac-ip>:8443/
#
# Zero-install alternative: just use https://vdo.ninja on the phone + this Mac.
set -euo pipefail
DIR="$(cd "$(dirname "$0")" && pwd)"
VDO="$DIR/vdo"
REPO="https://github.com/steveseguin/vdo.ninja.git"   # official upstream
PORT="${PORT:-8443}"
CERT="$DIR/phone-mic/certs/cert.pem"; KEY="$DIR/phone-mic/certs/key.pem"

install() {
  if [ ! -f "$VDO/index.html" ]; then
    echo "cloning VDO.Ninja ($REPO)..."
    rm -rf "$VDO"; git clone --depth 1 "$REPO" "$VDO"
  fi
  echo "installed -> start with: $0 start"
}

start() {
  [ -f "$VDO/index.html" ] || { echo "not installed yet — run: $0 install" >&2; exit 1; }
  [ -f "$CERT" ] || { echo "no cert yet — start phone-mic once (./billo-audio.sh start) to create it" >&2; exit 1; }
  LAN=$(ipconfig getifaddr en0 2>/dev/null || true)
  echo "VDO.Ninja -> https://${LAN:-<mac-ip>}:$PORT/   (phones: tap 'Add your camera/mic'; trust the cert once)"
  cd "$VDO"
  exec /usr/bin/python3 - "$PORT" "$CERT" "$KEY" <<'PY'
import http.server, ssl, sys
port, cert, key = int(sys.argv[1]), sys.argv[2], sys.argv[3]
srv = http.server.ThreadingHTTPServer(("0.0.0.0", port), http.server.SimpleHTTPRequestHandler)
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); ctx.load_cert_chain(cert, key)
srv.socket = ctx.wrap_socket(srv.socket, server_side=True)
srv.serve_forever()
PY
}

case "${1:-}" in
  install) install ;;
  start) start ;;
  *) echo "usage: $0 {install|start}"; exit 1 ;;
esac
