#!/usr/bin/env bash
# Launcher for the X2 dashboard agent. Sources ROS 2 and the AimDK workspace,
# then runs the agent. Used both interactively and by the systemd --user unit.
#
# Note: no `set -u` here. The ROS 2 setup scripts read variables that are not
# defined on a fresh shell (AMENT_TRACE_SETUP_FILES among them), so nounset
# makes sourcing them fail outright.

set -e

export RCUTILS_LOGGING_SEVERITY="${RCUTILS_LOGGING_SEVERITY:-ERROR}"
export ROS_DOMAIN_ID="${ROS_DOMAIN_ID:-0}"

# shellcheck disable=SC1091
source /opt/ros/humble/setup.bash

if [ -f "$HOME/aimdk/install/setup.bash" ]; then
    # shellcheck disable=SC1091
    source "$HOME/aimdk/install/setup.bash"
fi

# Fast DDS profile - REQUIRED for the camera and LiDAR topics.
#
# A camera frame off this robot is 170-430 KB and a LiDAR scan is 816 KB. Fast
# DDS defaults to a 512 KB shared-memory segment and small socket buffers, and
# it drops samples that large in complete silence: discovery succeeds, the
# reader matches the writer, `ros2 topic info` reports a publisher, and not one
# message is ever delivered. The vendor profile raises the SHM segment to 32 MB
# and the UDP buffers to 10 MB, which is the entire reason those topics work.
#
# This is why an earlier revision of backend/x2_spec.py concluded that the unit
# had one camera and no chest LiDAR. It has six feeds and a LiDAR; the agent
# just could not receive them without this line.
DDS_PROFILE="${FASTRTPS_DEFAULT_PROFILES_FILE:-/agibot/data/home/agi/.aima/env/ros_dds_configuration.xml}"
if [ -f "$DDS_PROFILE" ]; then
    export FASTRTPS_DEFAULT_PROFILES_FILE="$DDS_PROFILE"
else
    echo "[run_agent] WARNING: no DDS profile at $DDS_PROFILE - camera and LiDAR feeds will connect but deliver nothing" >&2
fi

# -u keeps the agent's own prints unbuffered so they reach the journal promptly.
# Fast DDS writes a very high volume of discovery chatter to stderr; the systemd
# unit sends stderr to /dev/null so it does not swamp the journal. Run this
# script by hand if you need to see it.
exec python3 -u "$(dirname "$(readlink -f "$0")")/x2_agent.py" "$@"
