#!/bin/bash

VPN_NAME="wg0"
HOME_ESSID="Alex's Vault"

interface=$1
status=$2

CURRENT_ESSID=$(iwgetid -r)

case $status in
  up|vpn-down)
    if [[ "$CURRENT_ESSID" != "$HOME_ESSID" ]]; then
      logger "[vpn-dispatch] Connected to '$CURRENT_ESSID'. Starting VPN '$VPN_NAME'."
      systemctl start wg-quick@$VPN_NAME
    else
      logger "[vpn-dispatch] On home network '$CURRENT_ESSID'. VPN not started."
    fi
    ;;
  down)
    if [[ "$CURRENT_ESSID" != "$HOME_ESSID" ]]; then
      if nmcli connection show --active | grep -q "$VPN_NAME"; then
        logger "[vpn-dispatch] Disconnected from '$CURRENT_ESSID'. Stopping VPN '$VPN_NAME'."
        systemctl stop wg-quick@$VPN_NAME
      fi
    else
      logger "[vpn-dispatch] On home network '$CURRENT_ESSID'. No VPN to stop."
    fi
    ;;
esac
