#!/bin/bash

PATH=/opt/mellanox/iproute2/sbin:/opt/mellanox/ethtool/sbin:/bin:/sbin:/usr/bin:/usr/sbin

has_rule() {
	if [ -n "$(ip $family rule list "$@")" ]; then
		# echo "Have: ip $family rule $*"
		return 0
	else
		# echo "Have not: ip $family rule $*"
		return 1
	fi
}

rule() {
	echo "Running: ip $family rule $*"
	ip $family rule "$@"
}

update_rules() {
	# move lookup local to pref 32765 (from 0)
	if ! has_rule pref 32765 lookup local; then
		rule add pref 32765 lookup local
	fi
	if has_rule pref 0 lookup local; then
		rule del pref 0 lookup local
	fi
	# make sure that in VRFs after failed lookup in the VRF specific table nothing else is reached
	if ! has_rule pref 1000 l3mdev; then
		# this should be added by the kernel when a VRF is created; add it here for completeness
		rule add pref 1000 l3mdev protocol kernel
	fi
	if ! has_rule pref 2000 l3mdev; then # can't search for actions; so can't make sure this is actually using "unreachable"
		rule add pref 2000 l3mdev unreachable
	fi
}

unset-systemd-foreign-policy-rules() {
    # systemd-networkd will delete foreign policy rules if not explicitely told not to
    if grep -q '^\s*#*\s*ManageForeignRoutingPolicyRules=' /etc/systemd/networkd.conf; then
        sudo sed -i '/^\s*#*\s*ManageForeignRoutingPolicyRules=/s/^#\?\s*//; s/=.*/=no/' /etc/systemd/networkd.conf
    else
        echo 'ManageForeignRoutingPolicyRules=no' >> /etc/systemd/networkd.conf
    fi
}

# up this mgmt interface
ip link set mgmt up
sleep 1
vrf configure mgmt 1001

unset-systemd-foreign-policy-rules

# invert route table lookup with ip rule so that lookup is done first in mgmt vrf before looking in local table
family=-4
update_rules
family=-6
update_rules