#!/bin/bash
# where the magic happens

CFG=~/.vpn-killswitch/config.cfg

# create the config file if it doesn't exist, in the user's home directory
# this is a duplication of gui functionality, the triggering of this condition assumes they're not using the gui
if [ ! -e ~/.vpn-killswitch/config.cfg ];
then

  mkdir ~/.vpn-killswitch

  # don't modify config here.  after first run, config.cfg is created in ~/.vpn-killswitch to modify
  DEFAULTS="
    DEBUG=FALSE               # excessive logging output to log file and terminal screen (when triggered direct) - use wisely!!
    IFCONFIG=/sbin/ifconfig   # whereis ifconfig
    INTERFACE=tun0            # ip a (while logged onto a vpn)
    CLIENT=deluge-gtk         # ps aux | grep [name of torrent client]
    CLI=FALSE                 # leave false/empty if you are using the desktop launcher method
  "
  echo -e "$DEFAULTS" > "$CFG"
fi

# shellcheck source=/dev/null
. "$CFG"
LOGPATH=~/.vpn-killswitch/"$CLIENT"-kill.log

function logMessage() {

  # always log to vpn-killswitch directory
  echo "$(date) $1" >> "$LOGPATH"
}

# run a test on the client, if it doesn't exist, the shell will crash
if [ "$(whereis "$CLIENT" | awk '{print $2}')" == "" ];
then
  if [ -f /usr/bin/notify-send ];
  then
    notify-send -i error "VPN Killswitch Configuration Error" \
    -u critical \
    "The client: $CLIENT specified in the killswitch config is incorrect. \
    \rSee $LOGPATH for details."
  fi

  logMessage "Unable to detect $CLIENT client.  Please check the config in $CFG for accuracy"
  exit 1
fi

# if the client is running already, a torrent dl might be being passed as an argument (%U), so feed it to the client and die
if [ ! "$(pgrep -a "$CLIENT")" == "" ] && [ "$CLI" == "FALSE" ];
then

  "$CLIENT" "$1"
  exit 0
fi

function extinct() {

  logMessage "${INTERFACE} interface or ${CLIENT} process is down, terminating ${CLIENT} to be safe..."

  if [ "$CLI" == "TRUE" ];
  then
    echo -e "\e[31m${INTERFACE} interface or ${CLIENT} missing, performing a kill signal...\e[0m"
  else

    # throw a notification on desktop that the vpn signal was lost
    if [ -f /usr/bin/notify-send ];
    then
      notify-send -i error "VPN Connection Lost, Killswitch Activated" \
      -u critical \
      "See $LOGPATH\
      \rfor details."

      logMessage "VPN Killswitch has been initiated"
    fi
  fi

  # forcefully terminate, otherwise if we wait for it to gracefully close, there's risk of exposure outside of the vpn
  pkill -f "$CLIENT" -9
  # for good measure, clean exit
  exit 0
}


function vpnCheck() {
  if [ "$DEBUG" == "TRUE" ];
  then
    logMessage "vpnCheck function triggered"
  fi

  # trigger an infinite loop, until the client is closed or tunnel is dropped
  while true;
    do
      sleep 1

      if [ ! "$($IFCONFIG | grep "$INTERFACE")" == "" ] && [ ! "$(pgrep -a "$CLIENT")" == "" ]; then

        # everything is working, do nothing
        if [ "$DEBUG" == "TRUE" ];
        then
          logMessage "${CLIENT} and ${INTERFACE} are active"
        fi
      else

        # no tunnel or client process detected; terminating
        extinct
      fi
    done
}

### startup
if [ "$DEBUG" == "TRUE" ];
then
  logMessage "VPN Killswitch has been initiated"
fi

if [ "$CLI" == "FALSE" ];
then
  # launch the torrent client as it's own parent process
  nohup "$CLIENT" &
else
  # give the torrent client a moment to boot before we start thumping out processes
  echo -e "\e[32m>> VPN Killswitch has been initiated! <<\e[0m  \nIf $CLIENT isn't boot immediately after the killswitch is launched, it will be terminated; so start services accordingly!"
  sleep 5
fi

vpnCheck
