#!/bin/bash

HOST_TOOLS="$( cd "$( dirname "$0" )" && pwd )"
VEHICLE_TOOLS=/mnt/mmc/LRAUV/Tools

NAMES="tethys lrauv-tethys daphne lrauv-daphne makai lrauv-makai ahi lrauv-ahi aku lrauv-aku opah lrauv-opah lrauv-whoidhs whoidhs" 
if [ $# -ne 1 ]; then
  echo "on-tether.sh requires a vehicle name as an argument";
  vehicle="_UNDEFINED_";
else
  vehicle=$1
fi

if echo "$NAMES" | grep -q "$vehicle"; then
  echo "safing $vehicle";
else
  echo "vehicle name $vehicle invalid";
  echo "valid vehicle names:";
  echo $NAMES;
  exit 0;
fi

## make Tools scripts executable (they are not when at sea, just in case)
echo "making Tools scripts on vehicle executable"
ssh $vehicle "nohup chmod ugo+x $VEHICLE_TOOLS/* &> /dev/null &"
## try to exit the application cleanly
echo "trying to exit the application cleanly"
ssh $vehicle "screen -S app -X stuff $'quit\n'"
sleep 5s
## kill LRAUV application (if running)
echo "killing any remaining instances of LRAUV application"
ssh $vehicle "killall LRAUV"
## run scripts to keep vehicle from rebooting
echo "running script to toggle heartbeat in absence of application"
ssh $vehicle "nohup $VEHICLE_TOOLS/toggleHeartbeat.sh &> /dev/null &"
echo "running scripts to disable wqatchdog timer and emergency circuit"
ssh $vehicle "nohup $VEHICLE_TOOLS/disableWDT.sh &> /dev/null &"
ssh $vehicle "nohup $VEHICLE_TOOLS/disableEmergency.sh &> /dev/null &"

