#!/bin/bash
# Start mediamtx RTSP server and ffmpeg test pattern publishers.
#
# Environment variables:
#   NUM_STREAMS  Number of test streams (1-4, default: 4)
#   RTSP_PORT    RTSP listen port (default: 8554)

set -e

NUM_STREAMS=${NUM_STREAMS:-4}
RTSP_PORT=${RTSP_PORT:-8554}

# Clamp to 1-4
[ "$NUM_STREAMS" -lt 1 ] && NUM_STREAMS=1
[ "$NUM_STREAMS" -gt 4 ] && NUM_STREAMS=4

# Stream configs: resolution, fps, color, label
STREAM_RES=("1920x1080" "1920x1080" "1280x720" "1280x720")
STREAM_FPS=("15"         "15"        "15"       "10")
STREAM_CLR=("0x2E86C1"   "0x28B463"  "0xD4AC0D" "0xCB4335")
STREAM_LBL=("Test Cam 1 - Front Door"
            "Test Cam 2 - Parking Lot"
            "Test Cam 3 - Loading Dock"
            "Test Cam 4 - Office")

# Update mediamtx port if overridden
if [ "$RTSP_PORT" != "8554" ]; then
    sed -i "s/:8554/:${RTSP_PORT}/" /etc/mediamtx.yml
fi

echo "Starting mediamtx RTSP server on :${RTSP_PORT}..."
mediamtx /etc/mediamtx.yml &
MEDIAMTX_PID=$!
sleep 2

if ! kill -0 $MEDIAMTX_PID 2>/dev/null; then
    echo "ERROR: mediamtx failed to start"
    exit 1
fi

# Start ffmpeg publishers
PIDS=()
for i in $(seq 0 $((NUM_STREAMS - 1))); do
    CAM_NUM=$((i + 1))
    RES="${STREAM_RES[$i]}"
    FPS="${STREAM_FPS[$i]}"
    CLR="${STREAM_CLR[$i]}"
    LBL="${STREAM_LBL[$i]}"
    W="${RES%x*}"
    H="${RES#*x}"

    echo "Starting cam${CAM_NUM}: ${RES} ${FPS}fps - ${LBL}"

    ffmpeg -hide_banner -loglevel warning \
        -re -f lavfi -i "testsrc2=size=${RES}:rate=${FPS}" \
        -vf "drawtext=text='${LBL}':fontsize=36:fontcolor=white:borderw=2:bordercolor=black:x=(w-text_w)/2:y=30, \
             drawtext=text='%{localtime}':fontsize=28:fontcolor=white:borderw=2:bordercolor=black:x=(w-text_w)/2:y=h-60, \
             drawtext=text='cam${CAM_NUM} ${RES} ${FPS}fps':fontsize=20:fontcolor=${CLR}:x=20:y=h-30" \
        -c:v libx264 -preset ultrafast -tune zerolatency \
        -b:v 2000k -maxrate 2500k -bufsize 4000k \
        -pix_fmt yuv420p -g $((FPS * 2)) \
        -f rtsp "rtsp://127.0.0.1:${RTSP_PORT}/cam${CAM_NUM}" &
    PIDS+=($!)
    sleep 1
done

echo ""
echo "========================================"
echo " NVR Test Camera Server"
echo "========================================"
echo " Streams: ${NUM_STREAMS}"
echo " RTSP:    :${RTSP_PORT}"
echo ""
for i in $(seq 0 $((NUM_STREAMS - 1))); do
    CAM_NUM=$((i + 1))
    echo "   rtsp://HOST:${RTSP_PORT}/cam${CAM_NUM}  (${STREAM_RES[$i]} ${STREAM_FPS[$i]}fps)"
done
echo ""
echo " NVR Device DB path: rtsp://127.0.0.1:${RTSP_PORT}/cam@@DEVICE@@"
echo "========================================"

# Trap shutdown and clean up
cleanup() {
    echo "Shutting down..."
    for pid in "${PIDS[@]}"; do
        kill "$pid" 2>/dev/null
    done
    kill $MEDIAMTX_PID 2>/dev/null
    wait
    exit 0
}
trap cleanup SIGTERM SIGINT

# Wait for mediamtx (if it dies, everything should stop)
wait $MEDIAMTX_PID
