#!/bin/bash

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3


# This script is used to integrate Window Switch with an existing iptables firewall.
# Global settings are stored in /etc/winswitch/firewall
#
# It will be called with one of these 3 forms:
# * winswitch_firewall ADD IP PORT
#	To add a new IP/port. If the default firewall rule is to block by default, no action should be necessary.
#   Otherwise, it will block this port.
# * winswitch_firewall ALLOW FROM_IP IP PORT
#	To allow a client to connect from FROM_IP to IP:PORT
# * winswitch_firewall REMOVE FROM_IP IP PORT
#	To remove the access previously granted via ALLOW.
#

SETTINGS="/etc/winswitch/firewall"

COMMAND=$1
if [ "${COMMAND}" == "ALLOW" ] || [ "${COMMAND}" == "REMOVE" ]; then
	FROM_IP=$2
	if [ -z "${FROM_IP}" ]; then
		echo "Missing FROM_IP"
		exit 1
	fi
	IP=$3
	PORT=$4
elif [ "${COMMAND}" == "ADD" ]; then
	FROM_IP="n/a"
	IP=$2
	PORT=$3
else
	echo "Invalid command: $1"
	exit 1
fi

if [ ! -r "${SETTINGS}" ]; then
	echo "${SETTINGS} is missing..."
	exit 1
fi

source ${SETTINGS}
iptables=`which iptables`
if [ -z "${iptables}" ]; then
	echo "cannot find iptables!"
fi
if [ `id -u` != "0" ]; then
	iptables="sudo ${iptables}"
fi

if [ "${FIREWALL_ENABLED}" != "1" ]; then
	echo "firewall disabled globally"
	exit 0
fi

if [ "${FROM_IP}" == "0.0.0.0" ]; then
	FROM_IP="0.0.0.0/0"
else
	FROM_IP="${FROM_IP}/32"
fi
if [ "${IP}" == "0.0.0.0" ]; then
	IP="0.0.0.0/0"
else
	IP="${FROM_IP}/32"
fi


echo "COMMAND=${COMMAND}, FROM_IP=${FROM_IP}, IP=${IP}, PORT=${PORT}"


# This bit should be converted to use substituted strings from /etc/winswitch/firewall....

for CHAIN in ${TARGET_CHAINS}; do
	CMD=""
	if [ "${COMMAND}" == "ADD" ]; then
		if [ "${MUST_BLOCK}" == "1" ]; then
			CMD="${iptables} -D ${CHAIN} -p TCP -s 0.0.0.0/0 -d ${IP} --dport ${PORT} -j DROP"
			echo $CMD
			$CMD
			CMD="${iptables} -I ${CHAIN} -p TCP -s 0.0.0.0/0 -d ${IP} --dport ${PORT} -j DROP"
			echo $CMD
			$CMD
		else
			echo MUST_BLOCK=${MUST_BLOCK}
		fi
	else
		#Always remove
		CMD="${iptables} -D ${CHAIN} -p TCP -s ${FROM_IP} -d ${IP} --dport ${PORT}"
		echo $CMD
		$CMD
		if [ "${COMMAND}" == "ALLOW" ]; then
			CMD="${iptables} -I ${CHAIN} -p TCP -s ${FROM_IP} -d ${IP} --dport ${PORT} -j ACCEPT"
			echo $CMD
			$CMD
		fi
	fi
done
exit 0
