#!/bin/bash

# Get the SD device of the Vecfever:
read -a DRIVE <<< "`lsblk|grep ^sd|fgrep K`"
SD="`echo ${DRIVE[0]}`"

if [ "$1" == "on" ] ; then
  # needs pub key .ssh/id_rsa.pub generated with "ssh-keygen -t rsa" and appended to gtoal@192.168.2.251:.ssh/authorized_keys2
    ssh gtoal@192.168.2.251 tp-link logger on
    sleep 15
    read -a DRIVE <<< "`lsblk|grep ^sd|fgrep K`"
    SD="`echo ${DRIVE[0]}`"
    if [ "$SD" == "" ] ; then
      echo "MAKE SURE THE VF USB IS PLUGGED IN!"
      exit 1
    fi
    exit 0
elif [ "$1" == "off" ] ; then
  ssh gtoal@192.168.2.251 tp-link logger off
  exit 0
elif [ "$1" != "" ] ; then
  if [ "$SD" == "" ] ; then
      echo "Resetting the Vectrex with \"$0 off ; $0 on ; $0 $1\""
      $0 off ; $0 on ; $0 $1
  else
    # WRONG. echo "The eject will work if the VF is in \"Start On Eject\" mode, not \"Buttons & Eject\" mode!"
    echo "USB has to be attached to the VF when it resets.  USB has to be disconnected to switch modes."
    mkdir -p vf  
    sudo mount /dev/$SD vf
    sudo cp $1 vf/CART.BIN
    sudo ls vf
    sudo umount /dev/$SD
    sudo sdparm --command=eject /dev/$SD
    echo "REMEMBER TO RESET THE VECTREX WHEN DONE TESTING SO THAT IT IS READY FOR THE NEXT UPLOAD!"
    # (but if you don't, I'll reset it the hard way with the remote power switch)
  fi
else
  echo "$0 [on | off | filename.bin]"
  exit 1
fi


#sg_start -s /dev/sdb
#hdparm -F /dev/sdb ; hdparm -Y /dev/sdb
#sudo eject /dev/sdX
#sudo udisksctl power-off -b /dev/sdb
##udisks --detach /dev/sdb
