#!/bin/sh
set -e

BIN_DIR=/mnt/flash/plus/kp_firmware/kp_firmware_0/kp_firmware/bin
FW=/mnt/flash/vienna/kp_firmware_host_stream
INI=$BIN_DIR/ini/host_stream.ini

cd $BIN_DIR

# Load hardware drivers if not already loaded (required for EDMC/NPU)
[ -e /dev/vpl_edmc ] || (cd /mnt/flash/vienna/drivers && sh driver.sh 2>/dev/null && sleep 1)

killall -9 kp_firmware_host_stream 2>/dev/null || true
killall -9 rtsps 2>/dev/null || true
sleep 1
rm -f /dev/shm/*

# Optional overrides:
#   PIXFMT=NV21 INF_STREAM=0 MODEL_PATH=nef/other.nef MODEL_ID=xxxxx JOB_ID=yyy ./demo_rtsp.sh
PIXFMT=${PIXFMT:-NV12}
INF_STREAM=${INF_STREAM:-1}

# Model settings — read from INI as default, env var overrides at runtime
_ini_val() { grep "^$1" "$INI" | sed 's/.*= *//' | tr -d '"' | awk '{print $1}'; }
MODEL_PATH=${MODEL_PATH:-$(_ini_val ModelPath)}
MODEL_ID=${MODEL_ID:-$(_ini_val ModelId)}
JOB_ID=${JOB_ID:-$(_ini_val JobId)}

# RTSP demo profile: single-process source + one encoder stream + RTSP server.
sed -i 's/^NnmSource.*/NnmSource = 0/' $INI
sed -i 's/^GetImageBufMode.*/GetImageBufMode = 0/' $INI
sed -i "s/^InferenceStream.*/InferenceStream = ${INF_STREAM}/" $INI
sed -i 's/^StreamCount.*/StreamCount = 2/' $INI
sed -i "s/^PixFmt.*/PixFmt = ${PIXFMT}/" $INI
sed -i 's/^voc_enable.*/voc_enable = 0/' $INI
# DrawBoxEnable: respect INI value set by web UI (do not override)

echo "=== RTSP Demo INI ==="
grep -E "ModelPath|ModelId|JobId|NnmSource|GetImageBufMode|InferenceStream|StreamCount|voc_enable|PixFmt|DrawBoxEnable" $INI
echo "=== Model (runtime): MODEL_PATH=$MODEL_PATH MODEL_ID=$MODEL_ID JOB_ID=$JOB_ID ==="

echo "=== Start Firmware (RTSP demo) ==="
LD_LIBRARY_PATH=/mnt/flash/vienna/lib $FW -m "$MODEL_PATH" -i "$MODEL_ID" -j "$JOB_ID" &
FW_PID=$!

sleep 4

# Start RTSP server that reads venc_srb_* output.
LD_LIBRARY_PATH=/mnt/flash/vienna/lib ./rtsps -c stream_server_config.ini &
RTSP_PID=$!

echo "Firmware PID: $FW_PID"
echo "RTSP PID: $RTSP_PID"
echo "RTSP URL: rtsp://192.168.3.10/live1.sdp"

wait $FW_PID
