#!/bin/sh
#
# This file is part of OpenMediaVault.
#
# @license   http://www.gnu.org/licenses/gpl.html GPL Version 3
# @author    Volker Theile <volker.theile@openmediavault.org>
# @copyright Copyright (c) 2009-2012 Volker Theile
#
# OpenMediaVault is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# OpenMediaVault is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with OpenMediaVault. If not, see <http://www.gnu.org/licenses/>.

# Documentation/Howto:
# https://help.ubuntu.com/community/IptablesHowTo
# http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_:_Ch14_:_Linux_Firewalls_Using_iptables
# http://www.cyberciti.biz/tips/linux-iptables-how-to-specify-a-range-of-ip-addresses-or-ports.html

set -e

. /etc/default/openmediavault
. /usr/share/openmediavault/scripts/helper-functions

OMV_IPTABLES_CONFIG=${OMV_IPTABLES_CONFIG:-"/etc/network/if-pre-up.d/iptables"}

cat <<EOF > ${OMV_IPTABLES_CONFIG}
#!/bin/sh
# ifpreup hook script for iptables
# Generated by OpenMediaVault

iptables -t filter -F
EOF

xmlstarlet sel -t \
  -m "//system/network/iptables/rule" -s A:N rulenum \
	-o "iptables" \
	-v "concat(' -A ',chain)" \
	-i "starts-with(protocol,'!')" \
		-v "concat(' ! -p ',translate(protocol,'!',''))" \
	-b \
	-i "not(starts-with(protocol,'!'))" \
		-v "concat(' -p ',protocol)" \
	-b \
	-i "string-length(source) > 0" \
	  -i "contains(source,'-')" \
		-o " -m iprange" \
		-i "starts-with(source,'!')" -o " !" -b \
		-o " --src-range " \
		-v "translate(source,'!','')" \
	  -b \
	  -i "not(contains(source,'-'))" \
		-o " -s " \
		-i "starts-with(source,'!')" -o "! " -b \
		-v "translate(source,'!','')" \
	  -b \
	-b \
	-i "string-length(sport) > 0" \
	  -o " --sport " \
	  -i "starts-with(sport,'!')" -o "! " -b \
	  -v "translate(translate(sport,'!',''),'-',':')" \
	-b \
	-i "string-length(destination) > 0" \
	  -i "contains(destination,'-')" \
		-o " -m iprange" \
		-i "starts-with(destination,'!')" -o " !" -b \
		-o " --dst-range " \
		-v "translate(destination,'!','')" \
	  -b \
	  -i "not(contains(destination,'-'))" \
		-o " -d " \
		-i "starts-with(destination,'!')" -o "! " -b \
		-v "translate(destination,'!','')" \
	  -b \
	-b \
	-i "string-length(dport) > 0" \
	  -o " --dport " \
	  -i "starts-with(dport,'!')" -o "! " -b \
	  -v "translate(translate(dport,'!',''),'-',':')" \
	-b \
	-v "concat(' -j ',action)" \
	-i "string-length(extraoptions) > 0" -v "concat(' ',extraoptions)" -b \
	-n \
  -b \
  ${OMV_CONFIG_FILE} | xmlstarlet unesc >> ${OMV_IPTABLES_CONFIG}

chmod 755 ${OMV_IPTABLES_CONFIG}
