#!/bin/sh

# Common alterator-net-iptables options:
OPTS="-d"

# Modification flag
MODIFYED=0

# Set port redirection status
# argts: status
pr_control()
{
    local STATUS=`/usr/bin/alterator-net-iptables "$OPTS" pr status`
    if [ "$STATUS" != "$1" ]; then
        echo "Turn port redirection $1" 1>&2
        /usr/bin/alterator-net-iptables "$OPTS" pr "$1"
        MODIFYED=1
    fi
}

# Commit rules table to iptables
pr_commit()
{
    if [ -n "$MODIFYED" ] && [ "$MODIFYED" -gt 0 ]; then
        echo "Commit changes to iptables" 1>&2
        /usr/bin/alterator-net-iptables write
        MODIFYED=0
    fi
}

OLDRULES=

# Delete old rules
pr_delete_old()
{
    if [ -s "$OLDRULES" ]; then
        cat "$OLDRULES" | \
          while read f t; do
            echo "Delete old port redirection rule: $f $t" 1>&2
            /usr/bin/alterator-net-iptables "$OPTS" pr del "$f" "$t"
          done
        MODIFYED=1
    fi
}

# Finalize the subsystem
pr_final()
{
    if [ -n "$OLDRULES" ] && [ -f "$OLDRULES" ]; then
        pr_delete_old
        rm "$OLDRULES"
        OLDRULES=
    fi
}

# Init the subsystem
pr_init()
{
    pr_final
}

# Add or replace a port redirection rule
# args: from to
pr_set()
{
    if [ -z "$OLDRULES" ]; then
        OLDRULES=`mktemp`
        /usr/bin/alterator-net-iptables "$OPTS" pr list > "$OLDRULES"
    fi

    if grep -q "^$1[[:space:]]\+$2" "$OLDRULES"; then
        sed -i -e "/^$1[[:space:]]\+$2/d" "$OLDRULES"
    else
        echo "Add new port redirection rule: $1 $2" 1>&2
        /usr/bin/alterator-net-iptables "$OPTS" pr add "$1" "$2"
        MODIFYED=1
    fi
}
