#!/usr/bin/env bash
# Keep the NPU runtime isolated from the system Python used by ROS Noetic.
set -uo pipefail

script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
camera_device="/dev/video0"
child_pid=""

# This is deliberately in the outer process: rknnlite/rospy shutdown may not
# run Python callbacks after roslaunch sends SIGINT.  The profile is global to
# the USB camera, so always leave it in the normal automatic state on exit.
restore_camera_profile() {
  v4l2-ctl -d "$camera_device" --set-ctrl=exposure_auto=3 >/dev/null 2>&1 || true
  v4l2-ctl -d "$camera_device" --set-ctrl=exposure_auto_priority=0 >/dev/null 2>&1 || true
  v4l2-ctl -d "$camera_device" --set-ctrl=white_balance_temperature_auto=1 >/dev/null 2>&1 || true
  v4l2-ctl -d "$camera_device" --set-ctrl=brightness=0 >/dev/null 2>&1 || true
  v4l2-ctl -d "$camera_device" --set-ctrl=contrast=50 >/dev/null 2>&1 || true
  v4l2-ctl -d "$camera_device" --set-ctrl=saturation=50 >/dev/null 2>&1 || true
  v4l2-ctl -d "$camera_device" --set-ctrl=gamma=300 >/dev/null 2>&1 || true
  echo "traffic_sign_node: camera profile restored to automatic exposure" >&2
}

forward_shutdown() {
  if [[ -n "$child_pid" ]]; then
    kill -INT "$child_pid" 2>/dev/null || true
    wait "$child_pid" 2>/dev/null || true
  fi
  exit 0
}

trap restore_camera_profile EXIT
trap forward_shutdown INT TERM

/home/ucar/venv3.9/bin/python3 "$script_dir/traffic_sign_node.py" "$@" &
child_pid=$!
wait "$child_pid"
exit $?
