#!/bin/bash

if [ $# -ne 1 ]; then
  echo "on-tether.sh requires a vehicle name as an argument";
  echo "valid arguments:";
  grep "Host " ~/.ssh/config | grep lrauv | grep -v cell;
else
  vehicle=$1
fi

echo "disabling WDT"
ssh $vehicle "devmem2 0x400040bc h 0x1 && devmem2 0x4003c00c h 0;devmem2 0x4003c004 h 0;devmem2 0x4003c014 h 0;devmem2 0x400040bc h 0" 1>/dev/null
echo "disabling emergency radio"
ssh $vehicle "devmem2 0x40028008 w 0x4000000 && sleep .1;devmem2 0x40028004 w 0x4000000" 1>/dev/null
#echo "clearing the burnwire"
#ssh $vehicle "devmem2 0x40028008 w 0x2000000 && sleep .1;devmem2 0x40028004 w 0x2000000" 1>/dev/null

echo "toggling heartbeat in a screen session on the vehicle"
ssh $vehicle screen -S toggleHeartbeat -d -m 'sh -c "while true;do date;devmem2 0x40028004 w 0x2000;sleep 5;date;devmem2 0x40028008 w 0x2000;sleep 5;done"'
# this can then be killed by killing the screen instance or by attatching it and hitting CTRL-C
#ssh $vehicle "screen -ls;screen -ls | grep toggleHeartbeat | cut -d '.' -f 1 | xargs kill -9;screen -ls;screen -wipe"
# or
#ssh $vehicle "ps -o pid,cmd -C screen | grep toggleHeartbeat | cut -d ' ' -f 1 | xargs kill -9;screen -wipe"

echo "trying to exit the application cleanly"
ssh $vehicle "screen -S app -X stuff $'quit\n'"
sleep 5s

echo "killing any remaining instances of LRAUV application"
ssh $vehicle "killall LRAUV"
