#!/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 a policy routing container for the given ${NAME}.

IPTABLES_UP="${NAME}_up"
IPTABLES_DOWN="${NAME}_down"
SAVE_DIRECTORY="/var/lib/bondingprivatewan/bonds"
test -f /etc/bonding/privatewan/${NAME} && . /etc/bonding/privatewan/${NAME}

start () {
    remove 2> /dev/null

    ip route add table $TABLE $VLAN_SUBNET dev $VLAN_IF scope link
    ip route add table $TABLE default via $VLAN_GW dev $VLAN_IF
    ip rule add prio $PRIO iif $VLAN_IF lookup $TABLE
    ip rule add prio $PRIO from $VLAN_SUBNET lookup $TABLE

    iptables -N $IPTABLES_DOWN 2> /dev/null
    iptables -I FORWARD -i $VLAN_IF -j $IPTABLES_DOWN
    iptables -A FORWARD -i $VLAN_IF -j DROP
    iptables -A ${IPTABLES_DOWN} -d $TUNNEL_BONDER_IP -j ACCEPT

    iptables -N $IPTABLES_UP 2> /dev/null
    iptables -I FORWARD -o $VLAN_IF -j $IPTABLES_UP
    iptables -A FORWARD -o $VLAN_IF -j DROP
    iptables -A ${IPTABLES_UP} -s $TUNNEL_BONDER_IP -j ACCEPT

    # Create a file in $SAVE_DIRECTORY, so that hooks for other bonds know there
    # is still another bond running in this policy routing container.
    mkdir -p $SAVE_DIRECTORY/$NAME
    touch $SAVE_DIRECTORY/$NAME/$ID
}
stop () {
    iptables -D ${IPTABLES_DOWN} -d $TUNNEL_BONDER_IP -j ACCEPT
    iptables -D ${IPTABLES_UP}   -s $TUNNEL_BONDER_IP -j ACCEPT

    rm $SAVE_DIRECTORY/$NAME/$ID

    # Only remove the policy routing container stuff if there are no other
    # bonds in the container.
    if ! [ "$(ls -A $SAVE_DIRECTORY/$NAME)" ]; then
        remove
    fi
}
remove () {
    # This is only called so we can remove everything before adding it back, or
    # when the last bond that is part of this policy routing container has
    # stopped. This ensures we don't get duplicate entries when we start the
    # second bond in a particular policy routing container.
    ip route del table $TABLE $VLAN_SUBNET dev $VLAN_IF  scope link
    ip route del table $TABLE default via $VLAN_GW dev $VLAN_IF
    ip rule del prio $PRIO iif $VLAN_IF lookup $TABLE
    ip rule del prio $PRIO from $VLAN_SUBNET lookup $TABLE

    iptables -D FORWARD -i $VLAN_IF -j $IPTABLES_DOWN
    iptables -D FORWARD -i $VLAN_IF -j DROP
    # If there's still something in the chain, then it can't be deleted and
    # this will fail.
    iptables -X ${IPTABLES_DOWN} 2> /dev/null

    iptables -D FORWARD -o $VLAN_IF -j $IPTABLES_UP
    iptables -D FORWARD -o $VLAN_IF -j DROP
    # If there's still something in the chain, then it can't be deleted and
    # this will fail.
    iptables -X ${IPTABLES_UP} 2> /dev/null

    true
}

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