#!/usr/bin/env bash
# Run inside the isolated ROS 2 Jazzy container described in the tutorial.
set -eo pipefail
source /opt/ros/jazzy/setup.bash
export RMW_IMPLEMENTATION=rmw_fastrtps_cpp
export ROS_DOMAIN_ID=71
work_dir=$(mktemp -d)
pub_pid=''
bad_pid=''
cleanup() {
  for pid in "$bad_pid" "$pub_pid"; do
    if [ -n "$pid" ]; then
      kill -INT "$pid" 2>/dev/null || true
      wait "$pid" 2>/dev/null || true
    fi
  done
  rm -rf "$work_dir"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
fail() { echo "FAIL: $*" >&2; cat "$work_dir"/*.log >&2; exit 1; }

common=(--qos-durability volatile --qos-history keep_last --qos-depth 10)
ros2 topic pub /qos_demo std_msgs/msg/String "{data: 'hello qos'}" \
  --node-name qos_demo_pub --rate 2 --wait-matching-subscriptions 0 \
  --qos-reliability best_effort "${common[@]}" > "$work_dir/publisher.log" 2>&1 &
pub_pid=$!

ros2 topic echo /qos_demo std_msgs/msg/String --once --timeout 10 --no-daemon \
  --qos-reliability best_effort "${common[@]}" > "$work_dir/baseline.log" 2>&1
grep -q '^data: hello qos$' "$work_dir/baseline.log" || fail 'Baseline received no sample'
echo 'BASELINE: best_effort -> best_effort received hello qos'

ros2 topic echo /qos_demo std_msgs/msg/String --once --timeout 15 --no-daemon \
  --qos-reliability reliable "${common[@]}" > "$work_dir/mismatch.log" 2>&1 &
bad_pid=$!
sleep 2
ros2 topic list -t --no-daemon --spin-time 2 > "$work_dir/topics.log"
ros2 topic info /qos_demo --verbose --no-daemon --spin-time 2 > "$work_dir/endpoints.log"
wait "$bad_pid" || fail 'Incompatible subscriber exited abnormally'
bad_pid=''
grep -q '/qos_demo \[std_msgs/msg/String\]' "$work_dir/topics.log" || fail 'Topic not discovered'
grep -qx 'Publisher count: 1' "$work_dir/endpoints.log" || fail 'Expected one publisher'
grep -qx 'Subscription count: 1' "$work_dir/endpoints.log" || fail 'Expected one subscriber during inspection'
grep -q 'Reliability: BEST_EFFORT' "$work_dir/endpoints.log" || fail 'Publisher profile missing'
grep -q 'Reliability: RELIABLE' "$work_dir/endpoints.log" || fail 'Subscriber profile missing'
grep -q 'RELIABILITY' "$work_dir/mismatch.log" || fail 'No incompatible reliability warning'
if grep -q '^data:' "$work_dir/mismatch.log"; then fail 'Incompatible subscriber received data'; fi
echo 'MISMATCH: topic and both endpoints discovered; RELIABILITY warning; no sample in 15 seconds'
echo '--- Endpoint inspection during mismatch ---'
cat "$work_dir/endpoints.log"
echo '--- Subscriber warning ---'
cat "$work_dir/mismatch.log"

ros2 topic echo /qos_demo std_msgs/msg/String --once --timeout 10 --no-daemon \
  --qos-reliability best_effort "${common[@]}" > "$work_dir/repair.log" 2>&1
grep -q '^data: hello qos$' "$work_dir/repair.log" || fail 'Repair received no sample'
echo 'REPAIR: best_effort -> best_effort received hello qos'
echo 'PASS: baseline, incompatible reliability, endpoint inspection, and repair'
