#!/usr/bin/env bash
set -euo pipefail

# Capture the 3 most promising CNNI streams simultaneously into browser-playable MP4s.
# Usage:
#   ./capture-cnni-all.sh                 # runs until Ctrl-C
#   ./capture-cnni-all.sh 1800            # stop after 1800 seconds
#   OUTDIR=./recordings ./capture-cnni-all.sh 600

DURATION="${1:-}"
OUTDIR="${OUTDIR:-./recordings}"
mkdir -p "$OUTDIR"

stamp="$(date +%Y%m%d_%H%M%S)"
run_dir="$OUTDIR/$stamp"
mkdir -p "$run_dir"

# Gateway URLs discovered from the recovered SceneTime playlist.
declare -A GATEWAY_URLS=(
  [usa_cnni_hd_east]='https://gohyperspeed.com/700418314/M1gbkj9t55/600006103'
  [pluto_germany_cnni]='https://gohyperspeed.com/700418314/M1gbkj9t55/700017805'
  [pluto_uk_cnni]='https://gohyperspeed.com/700418314/M1gbkj9t55/700017469'
)

declare -A LABELS=(
  [usa_cnni_hd_east]='USA: CNNi HD East'
  [pluto_germany_cnni]='(PLUTO Germany) CNNi'
  [pluto_uk_cnni]='(PLUTO UK) CNNi'
)

resolve_final_url() {
  local url="$1"
  curl -sSIL --max-time 20 -o /dev/null -w '%{url_effective}' "$url"
}

ffmpeg_duration_args=()
if [[ -n "$DURATION" ]]; then
  ffmpeg_duration_args=(-t "$DURATION")
fi

pids=()

graceful_stop() {
  echo
  echo "Stopping recordings..."
  for pid in "${pids[@]:-}"; do
    kill -INT "$pid" 2>/dev/null || true
  done
  wait || true
  echo "Saved recordings in: $run_dir"
}
trap graceful_stop INT TERM

echo "Output directory: $run_dir"
echo

for key in usa_cnni_hd_east pluto_germany_cnni pluto_uk_cnni; do
  gateway_url="${GATEWAY_URLS[$key]}"
  final_url="$(resolve_final_url "$gateway_url")"

  if [[ -z "$final_url" ]]; then
    echo "Failed to resolve: ${LABELS[$key]}"
    continue
  fi

  mp4="$run_dir/${key}.mp4"
  log="$run_dir/${key}.log"
  txt="$run_dir/${key}.txt"

  {
    echo "label=${LABELS[$key]}"
    echo "gateway_url=$gateway_url"
    echo "final_url=$final_url"
    echo "started_at=$(date --iso-8601=seconds)"
  } > "$txt"

  echo "Starting: ${LABELS[$key]}"
  echo "  gateway: $gateway_url"
  echo "  final:   $final_url"
  echo "  output:  $mp4"

  (
    exec ffmpeg -y -hide_banner -loglevel warning \
      "${ffmpeg_duration_args[@]}" \
      -i "$final_url" \
      -map 0 \
      -c copy \
      -movflags +faststart \
      -bsf:a aac_adtstoasc \
      "$mp4"
  ) > "$log" 2>&1 &

  pids+=("$!")
  echo

done

if [[ "${#pids[@]}" -eq 0 ]]; then
  echo "No recordings started."
  exit 1
fi

echo "All recordings started."
if [[ -n "$DURATION" ]]; then
  echo "Will stop automatically after $DURATION seconds."
else
  echo "Press Ctrl-C to stop and finalize MP4 files."
fi

echo
wait

echo "Saved recordings in: $run_dir"
