#!/bin/bash

DWALL_VERSION="0.5.0"

### Reading functions libary
source /usr/lib/dwall/hash-functions
source /usr/lib/dwall/dwall-functions
source /usr/lib/dwall/shared-functions

echo "Dwall v$DWALL_VERSION, running on $HOSTNAME by $(logname)"

### Verifying Dwall prerequisites.
dwall_verify

hash_clear alias
hash_clear zone

#packet_forwarding
#packet_routing
#log_martians
#route_verification
#syncookie

### Reading Prerouting rules
#source $CONFIGDIR/scripts/pre.sh

dwall_alias_hosts
hash_import alias "$CONFIGDIR/alias.conf"
hash_substitute alias is_address

hash_put alias all "0/0"
dwall_alias_self

echo -n $(hash_list alias | wc -w) "aliases, "
#hash_print alias

hash_import zone "$CONFIGDIR/zone.conf"
hash_substitute zone is_interface

hash_put zone self "lo"
hash_put zone $HOSTNAME "lo"
hash_put zone all "dummy"

echo -n $(hash_list zone | wc -w) "zones, "
#hash_print zone

### Reading services
nr=0
for servicefile in "$CONFIGDIR/services/"*; do
	source $servicefile
	nr=$((nr+1))
done
echo -n "$nr services "

(
	dwall_fw_init
	dwall_fw_targets
	dwall_fw_chains
	dwall_fw_exit
) > "$FIREWALL.new"


if [ $? -ne 0 -o "$ERROR" ]; then
	chmod u+x "$FIREWALL.new"
	mv -f "$FIREWALL.new" "$FIREWALL.error"
	echo "Incomplete firewall written to $FIREWALL.error"
else
	MD5OLD=$(md5sum "$FIREWALL" 2>/dev/null)
	MD5NEW=$(md5sum "$FIREWALL.new" 2>/dev/null)
	if [ "${MD5NEW/ */}" == "${MD5OLD/ */}" ]; then
		rm -f "$FIREWALL.new"
		echo "New rule set is identical to old rule set. Nothing done." >&2
	else
		chmod u+x "$FIREWALL.new"
		echo -n "Do you want to run the new Dwall rule set ? (N/y) "
		read answer
		if [ "$answer" != "y" ]; then
			echo "New Dwall rule set is saved at $FIREWALL.new" >&2
		else
			if [ -w "$FIREWALL" ]; then
				TIMESTAMP=$(date +'%Y%m%d-%H%M%S')
				echo "Archiving old rule set to backup/dwall.$TIMESTAMP" >&2
				mv -f "$FIREWALL" "$CONFIGDIR/backup/dwall.$TIMESTAMP"
			else
				echo "No existing rule set found, moving new rule set to $FIREWALL" >&2
			fi
			mv -f "$FIREWALL.new" "$FIREWALL"
			echo "Running $FIREWALL, please stand by." >&2
			$FIREWALL &> "$CONFIGDIR/output.tmp"
			if [ -s "$CONFIGDIR/output.tmp" ]; then
				echo "There are errors in $CONFIGDIR/output.tmp !"
			else
				echo "Done."
			fi
		fi
	fi
fi

die
