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

# check for device existance: ptp0, gps, spatial, pps
if [[ $(ls /dev/ | grep 'pps') = 'pps0' ]]; then
  echo "Found /dev/pps0!"
else
  echo "!!!!!!!!!! ERROR: no pps in /dev/"
  exit 1
fi
if [[ $(ls /dev/ | grep 'gps') = 'gps' ]]; then
  echo "Found /dev/gps!"
else
  echo "!!!!!!!!!! ERROR: no gps in /dev/"
  exit 1
fi
if [[ $(ls /dev/ | grep 'spatial') = 'spatial' ]]; then
  echo "Found /dev/spatial!"
else
  echo "!!!!!!!!!! ERROR: no spatial in /dev/ - check udev rules"
  exit 1
fi

echo 'note: this requires sudo for some commands'
echo 'you may need to edit /etc/sudoers and add:'
echo 'Defaults:yourlogin !tty_tickets'

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

echo "$(date) Starting ${SESSION}"
tmux new-session -d -s $SESSION

i=0

echo "setting up."
tmux select-window -t $SESSION:${i}
tmux rename-window -t $SESSION:${i} 'setup'
tmux send-keys "ptp/00_setup.sh" C-m
tmux send-keys "echo 'setup completed'" C-m
i=$((i+1))

sleep 20

echo "Starting gpsd."
tmux select-window -t $SESSION:${i}
tmux rename-window -t $SESSION:${i} 'gpsd'
tmux send-keys "ptp/10_gpsd.sh" C-m
tmux send-keys "sleep 10" C-m
tmux send-keys "echo 'see if gpsd is still running:'" C-m
tmux send-keys "ps ax | grep gpsd" C-m
i=$((i+1))

sleep 15

echo "Re-starting time server."
tmux new-window -t $SESSION:${i} -n "timeserver"
tmux send-keys "ptp/20_timeServer.sh" C-m
i=$((i+1))

sleep 10

echo "Starting ptp."
tmux new-window -t $SESSION:${i} -n 'ptp'
tmux send-keys "ptp/30_ptp4l.sh" C-m
i=$((i+1))

sleep 1

# change permissions on the PTP device
sudo chown root:dialout /dev/ptp0
sudo chmod a+r /dev/ptp0

echo "You should now be able to run cgps and ./30_watch_gps_time.sh"
echo '--------------------------------------'
echo "Running, press C^c to exit..."
echo "To attach to tmux session: sudo tmux a -t ${SESSION}"

sleep infinity
