#!/bin/bash
# Determine dirname of this file/directory
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
SESSION="adapt_live"

# NOTE: setup comms first (one time needed)
#nodes/setup_camera_comms.sh

# if this is run by root (startup/systemd) then delay for PTP
if (echo "${USER}" == "root") then
    echo "startup delay..."
    sleep 40
fi

# check for the rc_genicam_api install
list_genicam_devices="gc_config -l"
if ! command -v $list_genicam_devices &> /dev/null
then
    echo "It looks like the rc_genicam_api is not installed.  Run install_genicam.sh"
    exit 1
fi

# catch exiting the tmux session
trap "{
        echo Stopping TMUX Session;
        tmux kill-session -t ${SESSION};
        exit 0;
      }" EXIT


echo "$(date) Starting $SESSION"
tmux new -d -s $SESSION
i=0

echo "Starting roscore."
tmux select-window -t $SESSION:${i}
tmux rename-window -t $SESSION:${i} 'Roscore'
tmux send-keys "bash" C-m
tmux send-keys "source ../activate_ros.bash" C-m
tmux send-keys "nodes/roscore.sh" C-m
i=$((i+1))

sleep 1

echo "Setting up camera parameters."
tmux new-window -t $SESSION:${i} -n "camsetup"
tmux send-keys "bash" C-m
tmux send-keys "./40_change_camera_settings.sh && ./50_check_camera.sh" C-m
i=$((i+1))

sleep 45 # make sure this completes before the ROS image publisher

echo "Starting INS."
tmux new-window -t $SESSION:${i} -n 'INS'
tmux send-keys "bash" C-m
tmux send-keys "source ../activate_ros.bash" C-m
tmux send-keys "nodes/spatial.sh" C-m
i=$((i+1))

sleep 1

echo "Starting genicam publisher."
tmux new-window -t $SESSION:${i} -n "imgPub"
tmux send-keys "bash" C-m
tmux send-keys "source ../activate_ros.bash" C-m
tmux send-keys "nodes/genicam.sh" C-m
i=$((i+1))

sleep 5

echo "Starting ROS Segmentation Node."
tmux new-window -t $SESSION:${i} -n "SegmentationNode"
tmux send-keys "bash" C-m
tmux send-keys "source ../activate_ros.bash" C-m
tmux send-keys "nodes/segmentation.sh" C-m
i=$((i+1))

sleep 1

echo "Starting recorder service."
tmux new-window -t $SESSION:${i} -n "recorder"
tmux send-keys "bash" C-m
tmux send-keys "source ../devel/setup.bash" C-m
# change the compression to png
tmux send-keys "rosrun dynamic_reconfigure dynparam set /image_raw/compressed format png" C-m
tmux send-keys "nodes/recorder.sh" C-m
i=$((i+1))

sleep 1

echo "Starting Image translation."
tmux new-window -t $TMUX_SESSION:${i} -n 'Nexus'
tmux send-keys "bash" C-m
tmux send-keys "source ../activate_ros.bash" C-m
tmux send-keys "nodes/nexus.sh" C-m
i=$((i+1))

sleep 1

echo "Starting PTP Health and Diagnostics."
tmux new-window -t $TMUX_SESSION:${i} -n 'PTP Diagnostics'
tmux send-keys "bash" C-m
tmux send-keys "source ../activate_ros.bash" C-m
tmux send-keys "nodes/ptp_health.sh" C-m

echo "Running, press C^c to exit..."
echo "To attach to tmux session: sudo tmux a -t ${SESSION}"

sleep infinity
