#!/bin/sh
# Script to check your internet connection and if it's not OK
# then restart your network services. Make sure that you've the appropiates
# service names in the $services variable
#
# Autor: Eduard Toloza

# Define variables
services='systemd-networkd systemd-resolved randomvpn' #enable-processor-performance iwd
bond_active=$(ip -o link show type bond | awk -F': ' '{print $2}')

restart_network() {

  #Check if ping command is available
  if command -v ping > /dev/null; then
    # Check internet connection and if not OK then restart all networking services
    echo "Testing your connection..."
    if ! ping -q -c 1 -W 1 9.9.9.9 > /dev/null || ! systemctl is-active openvpn-client@*.service > /dev/null; then
      # Delete bond interfaces if they exists
      if [ ! -z "$bond_active" ] ; then
        for bond_iface in "$bond_active"; do
          ip link delete $bond_iface
          sleep 2 # time for the deletion before restarting network services
        done
      fi
      # Restart services
      echo "Your connection is not working, restarting your network services: $services"
      systemctl restart $services
      if [ $? -eq 0 ]; then
        echo "Services restarted sucessfully, leaving."
      else
        echo "An error has occurred, make sure that service names are correct."
      fi
    else
      echo "Your connection is OK"
    fi
  else
    echo "ping command is not available, aborting."
  fi
}

# Validate root permisions
if [ "$UID" != 0 ]; then
  echo "You don't have root permisions."
  exit
fi

# Check if the f options was passed to force restart of services
if [ "$1" == "f" ]; then
  sudo systemctl restart $services
  exit
fi

restart_network
