#!/bin/bash

# On boot this file gets executed several times with the IFACE environment variable filled in, so we only want to trigger this script when it equals the device that we configured this script for
# When manually calling this script, the IFACE environment variable is empty, so we check for any script arguments provided
if [ "$IFACE" = "${device}" ] || [ "$#" -gt "0" ]; then
  # On boot we don't have any script arguments, so we default to adding a route
  # When manually calling this script, we expect arguments provided
	cmd="add"
	if [ "$1" = "del" ]; then
		cmd="del"
	fi

	# On boot sleep 60 seconds to prevent "SIOCADDRT: Network is unreachable"
	# When manually calling this script with arguments provided, don't sleep as we want to persist the changes immediately
	if [ "$#" -eq "0" ]; then
		sleep 60
	fi

	if [ ! -z ${device} ]; then
		route $cmd -net ${network.staticroute.destination}/${network.staticroute.mask} gw ${network.staticroute.gateway} dev ${device} metric 10 && logger "Successfully added static route" || logger "Failed to add static route"
	else
		route $cmd -net ${network.staticroute.destination}/${network.staticroute.mask} gw ${network.staticroute.gateway} metric 10 && logger "Successfully added static route" || logger "Failed to add static route"
	fi
fi
exit 0
