#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

OS="`getos`"

if [ "${OS}" = "Ubuntu" ]; then
    if [ "`ufw status | grep Status | cut -d: -f2 | sed -e 's,^\s*,,g' -e 's,\s*$,,g'`" = "inactive" ]; then
        ufw enable
    fi
    ufw allow http
    ufw allow https
    ufw allow ssh
    ufw allow 8080/tcp
    ufw allow 9100/tcp
    ufw allow 631/tcp
    ufw allow 5432/tcp

    FOUND1=`grep "eth1:" /proc/net/dev`

    if  [ -n "$FOUND1" ] ; then
        ufw allow out on eth1 to any
        ufw allow in on eth1 from any
    fi

    FOUND2=`grep "eth2:" /proc/net/dev`

    if  [ -n "$FOUND2" ] ; then
        ufw allow out on eth2 to any
        ufw allow in on eth2 from any

        if grep -q '# disable broadcast traffic' /etc/ufw/after.rules; then
            echo "eth2 broadcast disabled already."
        else
            sed -i '/.*'\''COMMIT'\''.*/i # disable broadcast traffic to internal printer\n-A FORWARD -m pkttype --pkt-type broadcast -i eth2 -j DROP\n-A INPUT -m pkttype --pkt-type broadcast -i eth2 -j DROP\n\n' /etc/ufw/after.rules
        fi
    fi

    FOUND3=`grep "eth3:" /proc/net/dev`

    if  [ -n "$FOUND3" ] ; then
        ufw allow out on eth3 to any
        ufw allow in on eth3 from any
    fi

elif [ "${OS}" = "CentOS" ]; then
    /usr/sbin/lokkit -q \
        --default=server \
        --trust=em1 \
        -s http \
        -s https \
        -s ssh \
        -p 8080:tcp \
        -p 9100:tcp \
        -p 631:tcp \
        -p 5432:tcp
    /usr/sbin/lokkit -t eth+
    /usr/sbin/lokkit -t wlan+

    FOUND2=`grep "eth2:" /proc/net/dev`

    if  [ -n "$FOUND2" ] ; then
        iptables -D FORWARD -m pkttype --pkt-type broadcast -i eth2 -j DROP
        iptables -D INPUT -m pkttype --pkt-type broadcast -i eth2 -j DROP
        iptables -A FORWARD -m pkttype --pkt-type broadcast -i eth2 -j DROP
        iptables -A INPUT -m pkttype --pkt-type broadcast -i eth2 -j DROP
        service iptables save
    fi
else
    abort 2 "Unsupported OS: ${OS}"
fi
