#!/usr/bin/env bash
# Cheap GCP -> YouTube egress smoke test. Spins up a THROWAWAY CPU VM in the project, pushes a short
# test pattern (SMPTE-style colour bars + a 440 Hz tone) to YouTube over RTMPS with x264, then deletes
# the VM. Proves the two things that must work before the real GPU gateway is worth building:
#   1. the project's network egress can reach YouTube's RTMPS ingest, and
#   2. your YouTube live event + raw stream key are valid and accept an encoder.
# It does NOT test the 3D render or GPU/NVENC (that's the gateway VM, GATEWAY_VM.md) — just the pipe.
# Cost: an e2-standard-4 lives ~3-4 min => ~1 cent.
#
# Prereqs (yours, interactive — this script can't do them):
#   gcloud auth login                            # refresh credentials (non-interactive callers can't)
#   YouTube Studio -> Go Live -> Stream          # create a live event, copy its RAW stream key
#
# Run:
#   YOUTUBE_STREAM_KEY=xxxx-xxxx-xxxx-xxxx-xxxx v3/broadcast/deploy/smoke_youtube_egress.sh
#
# Watch YouTube Studio during the run: colour bars should appear within ~10-30 s (CDN latency) and
# health should read "excellent". The VM self-deletes when the test ends OR on Ctrl-C (trap).
#
# Overridable via env: PROJECT ZONE VM SECS RES FPS BITRATE_K MACHINE.
set -euo pipefail

: "${YOUTUBE_STREAM_KEY:?set YOUTUBE_STREAM_KEY (YouTube Studio -> Go Live -> Stream key)}"
PROJECT="${PROJECT:-apps-viewregatta}"
ZONE="${ZONE:-europe-north1-a}"
VM="${VM:-vr-egress-smoke}"
SECS="${SECS:-60}"
RES="${RES:-1920x1080}"
FPS="${FPS:-30}"
BITRATE_K="${BITRATE_K:-4500}"          # YouTube's recommended 1080p30 range is 3000-6000 kbps
MACHINE="${MACHINE:-e2-standard-4}"     # 4 vCPU sustains 1080p30 x264 veryfast in realtime

cleanup() {
    echo "[smoke] deleting throwaway VM $VM ..."
    gcloud compute instances delete "$VM" --project "$PROJECT" --zone "$ZONE" -q >/dev/null 2>&1 || true
}
trap cleanup EXIT

echo "[smoke] project=$PROJECT zone=$ZONE vm=$VM machine=$MACHINE  (key is masked in logs)"
echo "[smoke] creating throwaway VM (no service account, minimal scopes) ..."
gcloud compute instances create "$VM" --project "$PROJECT" --zone "$ZONE" \
    --machine-type "$MACHINE" --image-family ubuntu-2204-lts --image-project ubuntu-os-cloud \
    --boot-disk-size 20GB --no-service-account --no-scopes >/dev/null

echo "[smoke] waiting for SSH ..."
for _ in $(seq 1 30); do
    if gcloud compute ssh "$VM" --project "$PROJECT" --zone "$ZONE" --command "true" >/dev/null 2>&1; then
        break
    fi
    sleep 5
done

echo "[smoke] installing ffmpeg ..."
gcloud compute ssh "$VM" --project "$PROJECT" --zone "$ZONE" --command \
    "sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq && \
     sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq ffmpeg" >/dev/null

echo "[smoke] streaming ${SECS}s of ${RES}@${FPS} colour bars + tone to YouTube (RTMPS) ..."
# The stream key is passed as a remote env var (RK) so it is not baked into the ffmpeg argv on the VM.
gcloud compute ssh "$VM" --project "$PROJECT" --zone "$ZONE" --command \
    "RK='${YOUTUBE_STREAM_KEY}' ffmpeg -hide_banner -re \
        -f lavfi -i testsrc2=size=${RES}:rate=${FPS} \
        -f lavfi -i sine=frequency=440 \
        -c:v libx264 -preset veryfast -b:v ${BITRATE_K}k -maxrate ${BITRATE_K}k -bufsize $((BITRATE_K*2))k \
        -g $((FPS*2)) -pix_fmt yuv420p \
        -c:a aac -ar 44100 -b:a 128k \
        -t ${SECS} -f flv \"rtmps://a.rtmps.youtube.com/live2/\$RK\""

echo "[smoke] done. If YouTube Studio showed the bars + 'excellent' health, GCP -> YouTube egress works."
