#!/bin/bash
# DO NOT MODIFY THIS FILE. YOUR CHANGES WILL BE OVERWRITTEN WHEN BONDING IS UPGRADED.
# To extend this functionality add a new hook.

# Configure the route as part of the policy routing container ${NAME}.

IPTABLES_UP="${NAME}_up"
IPTABLES_DOWN="${NAME}_down"
SUBNET="${NETWORK}/${NETMASK}"
TUN_NAME="tun${BOND_ID}"
ROUTE_SAVE_DIRECTORY="/var/lib/bondingprivatewan/routes"
test -f /etc/bonding/privatewan/${NAME} && . /etc/bonding/privatewan/${NAME}
start () {
    remove 2> /dev/null

    ip rule add from $SUBNET iif $TUN_NAME table $TABLE prio $PRIO

    iptables -A ${IPTABLES_UP}   -s $SUBNET -i $TUN_NAME -o $VLAN_IF  -j ACCEPT
    iptables -A ${IPTABLES_DOWN} -d $SUBNET -i $VLAN_IF  -o $TUN_NAME -j ACCEPT

    # Save the details of the route to a file so that the tun hook can
    # can re-add the proper routing when it runs.
    mkdir -p $ROUTE_SAVE_DIRECTORY/$BOND_ID
    echo "TABLE=${TABLE}
SUBNET=${SUBNET}
TUN_NAME=${TUN_NAME}" > $ROUTE_SAVE_DIRECTORY/$BOND_ID/$ID
    # This will fail when the tunnel is down.
    ip route add table $TABLE $SUBNET dev $TUN_NAME 2> /dev/null || true
}
stop () {
    remove
}
remove () {
    ip route del table $TABLE $SUBNET dev $TUN_NAME 2> /dev/null || true
    rm $ROUTE_SAVE_DIRECTORY/$BOND_ID/$ID || true
    ip rule del from $SUBNET iif $TUN_NAME table $TABLE prio $PRIO
    iptables -D ${IPTABLES_UP}   -s $SUBNET -i $TUN_NAME -o $VLAN_IF  -j ACCEPT
    iptables -D ${IPTABLES_DOWN} -d $SUBNET -i $VLAN_IF  -o $TUN_NAME -j ACCEPT
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    *)
        echo "Usage: $0 {start|stop}"
        exit 1
        ;;
esac
