#!/bin/sh
#
if [ -d /var/run ] ; then
	PIDFILE=/var/run/ipmon.pid
else
	PIDFILE=/etc/opt/ipf/ipmon.pid
fi

id=`/usr/sbin/modinfo 2>&1 | awk '/ipf/ { print $1 } ' - 2>/dev/null`
if [ -f $PIDFILE ] ; then
	pid=`cat $PIDFILE 2>/dev/null`
else
	pid=`/bin/ps -e 2>&1 | awk '/ipmon/ { print $1 } ' - 2>/dev/null`
fi
PATH=${PATH}:/sbin:/opt/ipf/bin
IPFILCONF=/etc/opt/ipf/ipf.conf
IP6FILCONF=/etc/opt/ipf/ipf6.conf
IPNATCONF=/etc/opt/ipf/ipnat.conf

block_default_workaround() {
	ipf -F a
	echo "constructing minimal name resolution rules..."
	NAMESERVERS=`cat /etc/resolv.conf  2>/dev/null| \
		     nawk '/nameserver/ {printf "%s ", $2}' 2>/dev/null`
	if [ -z "$NAMESERVERS" ] ; then
		return
	fi
	for NS in $NAMESERVERS ; do
		IF_TO_NS=`/usr/sbin/route -n get $NS  2>/dev/null| \
			  nawk '$1 == "interface:" { print $NF ; exit }' \
			  2>/dev/null`
		if [ -z "$IF_TO_NS" ] ; then
			continue
		fi
		IP_TO_NS=`ifconfig $IF_TO_NS  2>/dev/null| \
			nawk 'NR == "2" { print $2 ; exit }' 2>/dev/null`
		if [ -z "$IP_TO_NS" ] ; then
			continue
		fi
		echo "pass out quick on $IF_TO_NS proto udp from $IP_TO_NS to $NS port = 53 keep state" | \
		ipf -f -
	done
}


load_ipf_config() {
	bad=0
	if [ -r ${IPFILCONF} ]; then
		if `/sbin/ipf -V | \
		      nawk '$1 == "Default:" && $2 == "pass" { exit 1 }'` ; then
			block_default_workaround
		fi
		ipf -IFa -f ${IPFILCONF}
		if [ $? != 0 ]; then
			echo "$0: load of ${IPFILCONF} into alternate set failed"
			bad=1
		fi
	fi
	if [ -r ${IP6FILCONF} ]; then
		ipf -6IFa -f ${IP6FILCONF}
		if [ $? != 0 ]; then
			echo "$0: load of ${IPFILCONF} into alternate set failed"
			bad=1
		fi
	fi
	if [ $bad -eq 0 ] ; then
		ipf -s -y
	else
		echo Not switching config due to load error.
	fi
}


load_ipnat_config() {
	if [ -r ${IPNATCONF} ]; then
		ipnat -CF -f ${IPNATCONF}
		if [ $? != 0 ]; then
			echo "$0: load of ${IPNATCONF} failed"
		else
			ipf -y
		fi
	fi
}


case "$1" in
	start)
		if [ x"$pid" != x ] ; then
			kill -TERM $pid 2>/dev/null
		fi
		if [ x$id != x ] ; then
			modunload -i $id 2>/dev/null
		fi
		modload /usr/kernel/drv/ipf
		ipf -y
		load_ipf_config
		load_ipnat_config
		ipmon -Ds
		;;

	stop)
		if [ x"$pid" != x ] ; then
			kill -TERM $pid
		fi
		if [ x$id != x ] ; then
			modunload -i $id
		fi
		;;

	reload)
		load_ipf_config
		load_ipnat_config
		;;

	reipf)
		load_ipf_config
		;;
	reipnat)
		load_ipnat_config
		;;
	*)
		echo "Usage: $0 (start|stop|reload|reipf|reipnat)" >&2
		exit 1
		;;

esac
exit 0
