wire 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env bash
  2. # -e option instructs bash to immediately exit if any command [1] has a non-zero exit status
  3. # we don't want to continue execution of the script if something is broken. This may potentially
  4. # complicate IP routing table entries which may require manual intervention to fix thereafter.
  5. set -e
  6. # Declare global variables here
  7. # Modify the variables in this section in conformity with the naming convention of your Mullvad
  8. # configuration files in /etc/wireguard
  9. mullvadVpnInterfaceRegex="mullvad-\w*"
  10. wireguardConfigurationDirectory="/etc/wireguard/"
  11. connectedWireguardConfiguration=""
  12. # A method to retrieve the current connected Mullvad interface.
  13. checkMullvadConnectivity() {
  14. # Check if Mullvad VPN is already connected.
  15. connectedWireguardConfiguration=$(ip addr | grep --word-regexp "$1" | cut -d " " -f 2 | tr -d ":")
  16. # Return an arbitrary integer value | This value is not checked right now
  17. return 0
  18. }
  19. checkMullvadConnectivity "$mullvadVpnInterfaceRegex"
  20. # Debug log
  21. # echo " ip addr command returned $connectedWireguardConfiguration"
  22. # Extract the wireguard configuration list that is available in /etc/wireguard
  23. newWireguardConfigurationList=$(sudo ls $wireguardConfigurationDirectory | grep --word-regexp "$mullvadVpnInterfaceRegex")
  24. # Pick a wireguard interface at random to connect to next
  25. newWireguardConfiguration=$(shuf -n 1 -e $newWireguardConfigurationList)
  26. # Satisfies this condition if a connected interface was found.
  27. if [[ -n "$connectedWireguardConfiguration" ]]; then
  28. echo "" # Blank space for formatting
  29. echo "Cron is re-configuring the connected VPN."
  30. echo "System is currently connected to $connectedWireguardConfiguration and switching over to $newWireguardConfiguration"
  31. sudo wg-quick down $connectedWireguardConfiguration 2> /dev/null
  32. sudo wg-quick up $wireguardConfigurationDirectory$newWireguardConfiguration 2> /dev/null
  33. checkMullvadConnectivity $mullvadVpnInterfaceRegex
  34. echo $connectedWireguardConfiguration
  35. # Satisfies this condition if a connected interface was not found.
  36. elif [[ -z "$connectedWireguardConfiguration" ]]; then
  37. echo "" # Blank space for formatting
  38. echo "Cron is configuring a VPN now."
  39. echo "System will attempt to connect to $newWireguardConfiguration"
  40. sudo wg-quick up $wireguardConfigurationDirectory$newWireguardConfiguration 2> /dev/null
  41. checkMullvadConnectivity $mullvadVpnInterfaceRegex
  42. echo $connectedWireguardConfiguration
  43. fi