#!/bin/sh
id=`/usr/sbin/modinfo | awk '/ipf/ { print $1 } ' -`
pid=`ps -e | awk '/ipmon/ { print $1 } ' -`
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 | nawk '/nameserver/ {printf "%s ", $2}'`
      for NS in $NAMESERVERS ; do
	      IF_TO_NS=`/usr/sbin/route -n get $NS | \
                           nawk '$1 == "interface:" { print $NF ; exit }'`
	      IP_TO_NS=`ifconfig $IF_TO_NS | \
                           nawk 'NR == "2" { print $2 ; exit }'`
	      echo "pass out quick proto udp from $IP_TO_NS to $NS port = 53 keep state" | \
		      ipf -f -
      done
}

case "$1" in
	start)
		if [ x"$pid" != x ] ; then
			kill -TERM $pid
		fi
		if [ x$id != x ] ; then
			modunload -i $id
		fi
		modload /usr/kernel/drv/ipf
		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"
			else
				ipf -s
			fi
		fi
		ipf -y
		if [ -r ${IP6FILCONF} ]; then
			ipf -IFa -6f ${IP6FILCONF}
			if [ $? != 0 ]; then
				echo "$0: load of ${IPFILCONF} into alternate set failed"
			else
				ipf -IF a
				ipf -6f ${IP6FILCONF}
			fi
		fi
		if [ -r ${IPNATCONF} ]; then
			ipnat -CF -f ${IPNATCONF}
			if [ $? != 0 ]; then
				echo "$0: load of ${IPNATCONF} failed"
			fi
		fi
		ipmon -s &
		;;

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

	reload)
		if [ -r ${IPFILCONF} ]; then
			ipf -I -Fa -f ${IPFILCONF}
			if [ $? != 0 ]; then
				echo "$0: reload of ${IPFILCONF} into alternate set failed"
			else
				ipf -s
			fi
		fi
		if [ -r ${IPNATCONF} ]; then
			ipnat -CF -f ${IPNATCONF}
			if [ $? != 0 ]; then
				echo "$0: reload of ${IPNATCONF} failed"
			fi
		fi
		;;

	reipf)
		if [ -r ${IPFILCONF} ]; then
			ipf -I -Fa -f ${IPFILCONF}
			if [ $? != 0 ]; then
				echo "$0: reload of ${IPFILCONF} into alternate set failed"
			else
				ipf -s
			fi
		fi
		;;
	*)
		echo "Usage: $0 (start|stop|reload)" >&2
		exit 1
		;;

esac
exit 0
