#!/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 override: PIXFMT=NV21 MODEL_PATH=nef/other.nef MODEL_ID=xxxxx JOB_ID=yyy ./demo_hdmi.sh
PIXFMT=${PIXFMT:-NV12}

# 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)}

# HDMI demo profile: inference on stream1 (724x362) + HDMI output from stream0 (1920x1080).
# InferenceStream=1: NPU receives 724x362 frames (model native res) — ~8x faster than InferenceStream=0.
# StreamCount=2: creates both stream0 (1920x1080, draw_box+HDMI) and stream1 (724x362, inference) SSMs.
sed -i 's/^NnmSource.*/NnmSource = 0/' $INI
sed -i 's/^GetImageBufMode.*/GetImageBufMode = 0/' $INI
sed -i 's/^InferenceStream.*/InferenceStream = 1/' $INI
sed -i 's/^StreamCount.*/StreamCount = 2/' $INI
sed -i 's/^voc_enable.*/voc_enable = 1/' $INI
sed -i "s/^PixFmt.*/PixFmt = ${PIXFMT}/" $INI
# DrawBoxEnable: respect INI value set by web UI (do not override)

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

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