#!/bin/bash

DWALL_VERSION="0.5.3"

### 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

### Clear all hashes
hash_clear mac alias zone

#packet_forwarding
#packet_routing
#log_martians
#route_verification
#syncookie

### Importing alias hash
dwall_hash_import alias "/etc/hosts"
hash_import alias "$CONFIGDIR/alias.conf"
hash_delete alias all; hash_put alias all "0/0"
dwall_alias_self
echo -n $(hash_list alias | wc -w) "aliases"
#hash_print alias

### Importing mac hash
dwall_hash_import mac "/etc/ethers"
echo -n "," $(hash_list mac | wc -w) "mac addresses"
#hash_print mac

### Importing zone hash
hash_import zone "$CONFIGDIR/zone.conf"
hash_subst zone is_interface
hash_delete zone self; hash_put zone self "lo"
echo -n "," $(hash_list zone | wc -w) "zones"
hash_delete zone $HOSTNAME; hash_put zone $HOSTNAME "lo"
#hash_delete zone all; hash_put zone all "dummy"
#hash_print zone

### Importing 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
	bash -n "$FIREWALL.new" &> "$CONFIGDIR/tmp/errors"
	if [ $? -ne 0 ]; then
		echo "New Dwall rule set '$FIREWALL.new' has syntax errors, see $CONFIGDIR/tmp/errors."
	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 as $FIREWALL.new" >&2
			else
				if [ ! -f "$FIREWALL" ]; then
					echo "No existing rule-set found, moving new rule-set to $FIREWALL" >&2
				else
					TIMESTAMP=$(date +'%Y%m%d-%H%M%S')
					echo "Archiving old rule-set to $CONFIGDIR/backup/dwall.$TIMESTAMP" >&2
					mv -f "$FIREWALL" "$CONFIGDIR/backup/dwall.$TIMESTAMP"
				fi
				mv -f "$FIREWALL.new" "$FIREWALL"
				echo "Running $FIREWALL, please stand by." >&2
				$FIREWALL &> "$CONFIGDIR/tmp/errors"
				if [ -s "$CONFIGDIR/tmp/errors" ]; then
					echo "There are errors in $CONFIGDIR/tmp/errors !"
				else
					echo "Done."
				fi
			fi
		fi
	fi
fi

die
