#!/usr/bin/env bash
# Upper computer: camera -> normalized ROS depth -> DDS, no robot control.
set -eo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HEALTH="$SCRIPT_DIR/depth_walk_camera_health.py"
APP_WS="${DEPTH_APP_WS:-$HOME/kuavo_ros_application}"
BRIDGE_WS="${DEPTH_BRIDGE_WS:-$HOME/leju_head_lab}"
[[ "$APP_WS" == /* ]] || APP_WS="$HOME/$APP_WS"
[[ "$BRIDGE_WS" == /* ]] || BRIDGE_WS="$HOME/$BRIDGE_WS"
STATE_DIR="${DEPTH_STATE_DIR:-$HOME/.cache/depth_walk_launcher}"
[[ "$STATE_DIR" == /* ]] || STATE_DIR="$HOME/$STATE_DIR"
USB_PORT="${DEPTH_USB_PORT:-auto}"
export ROS_MASTER_URI=http://localhost:11311
export ROS_IP="${DEPTH_ROS_IP:-192.168.26.12}"
export PYTHONUNBUFFERED=1
ACTION="${1:-start}"
[[ $# -le 1 ]] || { echo "Usage: $0 {start|stop|status|logs}" >&2; exit 2; }
case "$ACTION" in start|stop|status|logs) ;; *) echo "Usage: $0 {start|stop|status|logs}" >&2; exit 2 ;; esac

stop_owned() {
    local name pid owner
    for name in bridge processor camera roscore; do
        [[ -f "$STATE_DIR/$name.pid" ]] || continue
        pid="$(cat "$STATE_DIR/$name.pid")"
        if [[ "$pid" =~ ^[0-9]+$ ]] && [[ -r "/proc/$pid/environ" ]]; then
            # Do not kill an unrelated process if a stale PID has been reused.
            owner="$(tr '\0' '\n' < "/proc/$pid/environ" 2>/dev/null | grep -Fx "DEPTH_LAUNCH_OWNER=$STATE_DIR" || true)"
            if [[ -n "$owner" ]] && [[ "$(ps -o pgid= -p "$pid" | tr -d ' ')" == "$pid" ]]; then
                kill -INT -- "-$pid" 2>/dev/null || true
                for ((attempt=0; attempt<30; attempt++)); do
                    kill -0 "$pid" 2>/dev/null || break
                    sleep 0.1
                done
                kill -TERM -- "-$pid" 2>/dev/null || true
                echo "[upper] Stopped $name (PID $pid)"
            fi
        fi
        rm -f "$STATE_DIR/$name.pid"
    done
}
# Cleanup must remain available even when ROS/workspaces are broken.
if [[ "$ACTION" == stop ]]; then stop_owned; exit 0; fi
[[ -f /opt/ros/noetic/setup.bash ]] || { echo 'ROS Noetic setup missing' >&2; exit 1; }
[[ -f "$APP_WS/devel/setup.bash" && -f "$BRIDGE_WS/devel/setup.bash" && -f "$HEALTH" ]] || {
    echo 'Upper workspaces/helper missing; run deploy_depth_walk.sh --camera-only' >&2; exit 1;
}
source /opt/ros/noetic/setup.bash
source "$APP_WS/devel/setup.bash"
set -u
mkdir -p "$STATE_DIR"
# A stopped node can remain registered with rosmaster; require a live reply.
node_exists() {
    timeout 5 python3 -c 'import rosnode, sys; sys.exit(0 if rosnode.rosnode_ping(sys.argv[1], max_count=1, verbose=False) else 1)' "$1" >/dev/null 2>&1
}

if [[ "$ACTION" == status ]]; then
    for node in /camera/camera /depth_image_processor /processed_depth_camera_bridge; do
        if node_exists "$node"; then echo "$node: running"; else echo "$node: stopped"; fi
    done
    exit 0
fi
if [[ "$ACTION" == logs ]]; then
    # The SSH caller owns this foreground log session, not the camera processes.
    touch "$STATE_DIR/roscore.log" "$STATE_DIR/camera.log" "$STATE_DIR/processor.log" "$STATE_DIR/bridge.log"
    tail -n 8 -F "$STATE_DIR/"{roscore,camera,processor,bridge}.log &
    TAIL_PID=$!
    python3 -u "$HEALTH" watch &
    HEALTH_PID=$!
    finish_logs() { trap - EXIT; trap '' INT TERM HUP; kill "$TAIL_PID" "$HEALTH_PID" 2>/dev/null || true; wait "$TAIL_PID" "$HEALTH_PID" 2>/dev/null || true; }
    trap finish_logs EXIT
    trap 'exit 130' INT
    trap 'exit 143' TERM
    trap 'exit 129' HUP
    wait -n "$TAIL_PID" "$HEALTH_PID"
    exit 1
fi

wait_for_topic() {
    local topic="$1" i
    echo "[upper] Waiting for $topic..."
    for ((i=0; i<20; i++)); do
        if timeout 2 rostopic echo --noarr -n 1 "$topic" >/dev/null 2>&1; then return 0; fi
        sleep 1
    done
    echo "[upper] No messages on $topic; recent logs:" >&2
    tail -n 15 "$STATE_DIR/"*.log >&2 || true
    return 1
}
start_roslaunch() {
    local name="$1" workspace="$2" package="$3" launch="$4"; shift 4
    setsid env "DEPTH_LAUNCH_OWNER=$STATE_DIR" bash -c '
        source /opt/ros/noetic/setup.bash
        source "$1/devel/setup.bash"
        export ROS_MASTER_URI=http://localhost:11311 ROS_IP="$2" PYTHONUNBUFFERED=1
        exec roslaunch --screen "$3" "$4" "${@:5}"
    ' bash "$workspace" "$ROS_IP" "$package" "$launch" "$@" \
        >"$STATE_DIR/$name.log" 2>&1 </dev/null &
    echo "$!" >"$STATE_DIR/$name.pid"
    echo "[upper] Started $name (PID $!, log $STATE_DIR/$name.log)"
}
startup_failed() {
    local rc=$?
    trap - EXIT
    if [[ "$rc" -ne 0 ]]; then
        echo '[upper] Startup failed; stopping only this session’s nodes' >&2
        tail -n 12 "$STATE_DIR/"*.log >&2 2>/dev/null || true
        stop_owned
    fi
    exit "$rc"
}
# Noninteractive SSH does not inherit the systemd bridge service's DDS paths.
if [[ -z "${CYCLONEDDS_HOME:-}" ]]; then
    for prefix in "$BRIDGE_WS/3rd_party/aarch64-shared" "$HOME/Leju_head_ARM/3rd_party/aarch64-shared" /usr/local /usr; do
        if [[ -f "$prefix/lib/libddsc.so" ]]; then export CYCLONEDDS_HOME="$prefix"; break; fi
    done
fi
if [[ -n "${CYCLONEDDS_HOME:-}" ]]; then
    export LD_LIBRARY_PATH="$CYCLONEDDS_HOME/lib:${LD_LIBRARY_PATH:-}"
fi
if [[ -z "${CYCLONEDDS_URI:-}" ]]; then
    if [[ -f /etc/cyclonedds/cyclonedds.xml ]]; then
        export CYCLONEDDS_URI=file:///etc/cyclonedds/cyclonedds.xml
    else
        export CYCLONEDDS_URI="file://$BRIDGE_WS/src/ros_dds_bridge/config/cyclonedds_bridge.xml"
    fi
fi
python3 -c 'from cyclonedds.domain import DomainParticipant' || {
    echo '[upper] CycloneDDS unavailable; set CYCLONEDDS_HOME to the install prefix' >&2; exit 1;
}
echo "[upper] DDS library: ${CYCLONEDDS_HOME:-system}, config: $CYCLONEDDS_URI"
trap startup_failed EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
USB_PORT="$(python3 "$HEALTH" usb --port "$USB_PORT")"
echo "[upper 1/4] Head camera USB $USB_PORT, ROS master $ROS_MASTER_URI"
if ! rosparam get /run_id >/dev/null 2>&1; then
    setsid env "DEPTH_LAUNCH_OWNER=$STATE_DIR" bash -c 'source /opt/ros/noetic/setup.bash; exec roscore' \
        >"$STATE_DIR/roscore.log" 2>&1 </dev/null &
    echo "$!" >"$STATE_DIR/roscore.pid"
    for ((i=0; i<20; i++)); do
        rosparam get /run_id >/dev/null 2>&1 && break
        sleep 1
    done
    rosparam get /run_id >/dev/null 2>&1 || { echo 'roscore failed' >&2; exit 1; }
fi
if ! node_exists /camera/camera; then
    start_roslaunch camera "$APP_WS" orbbec_camera gemini_330_series_60hz_depth.launch "usb_port:=$USB_PORT"
else
    CURRENT_PORT="$(rosparam get /camera/camera/usb_port 2>/dev/null || true)"
    [[ "$CURRENT_PORT" == "$USB_PORT" ]] || { echo "Running camera uses USB '$CURRENT_PORT', expected '$USB_PORT'; stop that camera first" >&2; exit 1; }
    echo '[upper] Reusing camera node'
fi
wait_for_topic /camera/depth/image_raw
echo '[upper 2/4] Starting depth image processor'
if ! node_exists /depth_image_processor; then
    start_roslaunch processor "$APP_WS" depth_image_recorder process_depth_images.launch
else
    echo '[upper] Reusing depth processor'
fi
wait_for_topic /camera/depth/image_processed
echo '[upper 3/4] Starting processed depth DDS bridge'
if ! node_exists /processed_depth_camera_bridge; then
    start_roslaunch bridge "$BRIDGE_WS" ros_dds_bridge processed_depth_camera_bridge.launch
else
    echo '[upper] Reusing DDS bridge'
fi
for ((i=0; i<15; i++)); do
    node_exists /processed_depth_camera_bridge && break
    sleep 1
 done
node_exists /processed_depth_camera_bridge || { echo 'DDS bridge failed' >&2; exit 1; }
echo '[upper 4/4] Measuring raw/processed rates (5 seconds, target 60Hz)'
python3 -u "$HEALTH" check
echo '[upper] Depth pipeline ready: rt/depth_camera/frame_normalized_36x64'