#!/bin/sh

GUEST_OE_ADMIN_CONF="/etc/oe-admin.conf"
HOST_OE_ADMIN_CONF="${MEDIACASTER_DIR}${GUEST_OE_ADMIN_CONF}"

get_config () {
    grep "^$2 " "$1" | sed "s/^$2 \(.*\)/\1/g"
}

firewall_accept () {
    local IFNAME="$1"
    local PORTNAME="$2"
    local PORTNO="$3"

    firewall addport "$IFNAME" "$PORTNAME" TCP "$PORTNO" 2>/dev/null 1>/dev/null
    RETVAL=$?
    case ${RETVAL} in
        0)
            echo "Opened port $PORTNO on VPN interface"
            ;;
        1)
            echo "Invalid port $PORTNO"
            ;;
        2)
            echo "Port $PORTNO already in use"
            ;;
        *)
            echo "Unknown error $RETVAL while opening port $PORTNO"
            ERRORS=1
            ;;
    esac

    return ${ERRORS}
}

firewall_drop() {
    local IFNAME="$1"
    local PORTNAME="$2"
    local PORTNO="$3"

    firewall delport "$IFNAME" "$PORTNAME" TCP "$PORTNO" 2>/dev/null 1>/dev/null
    RETVAL=$?
    case ${RETVAL} in
        0)
            echo "Closed port $PORTNO on VPN interface"
            ;;
        1)
            echo "Invalid port $PORTNO"
            ;;
        2)
            echo "Port $PORTNO not in use"
            ;;
        *)
            echo "Unknown error $RETVAL while opening port $PORTNO"
            ERRORS=1
            ;;
    esac

    return ${ERRORS}
}

TUNInterface=$(get_config "${HOST_OE_ADMIN_CONF}" "TUNInterface")

case $1 in
    start)
        firewall_accept ${TUNInterface} Kwilt-VPN-HTTP 42080
        ;;

    stop)
        firewall_drop ${TUNInterface} Kwilt-VPN-HTTP 42080
        ;;
esac

exit $?
