#!/bin/bash
#
# Copyright (c) Citrix Systems 2017. All rights reserved.

set -e

#################################################
# Use this script to open/close port with specified
# protocol.
#
# Usage:
#   ./firewall-port {open|close} port protocol
#
#################################################

OP="$1"
PORT="$2"
PROTOCOL="${3:-tcp}"
RULE="-p $PROTOCOL -m conntrack --ctstate NEW -m $PROTOCOL --dport $PORT -j ACCEPT"

case "$PORT" in
    80)
        CHAIN="RH-Firewall-1-INPUT"
        ;;
    *)
        CHAIN="xapi-INPUT"
        ;;
esac

case "${OP}" in
    open)
        if ! iptables -C $CHAIN $RULE 2>/dev/null
        then # first ensure chain exists
            if  iptables -N "${CHAIN}" 2>/dev/null
            then #chain did not exist but does now
                iptables -A "${CHAIN}" -j RETURN
                iptables -I INPUT -j "${CHAIN}"
            fi # asuume chain is used if it exists
        iptables -I "${CHAIN}" $RULE
	/usr/libexec/iptables/iptables.init save
        fi
        ;;
    close)
        if iptables -C $CHAIN $RULE 2>/dev/null
        then # close port  if it was opened 
            iptables -D $CHAIN $RULE
	    /usr/libexec/iptables/iptables.init save
        fi
        ;;
    check) 
        if [[ -z `iptables -S $CHAIN | grep " $PORT "` ]]
        then
            echo "Port $PORT open: true"
        else
            echo "Port $PORT open: false"
        fi
        ;;
    *)
        echo $"Usage: $0 {open|close|check} {port} {protocol}" 1>&2
        exit 1
        ;;
esac

exit 0

