#!/bin/sh

if [ ! -f /etc/PG.conf ]; then
	echo "/etc/PG.conf not exist!"
	exit 1
fi

. /etc/PG.conf
. ${PGETC}/ifadmin.conf

FLOWEYE=${PGPATH}/bin/floweye
NATCMD=${PGPATH}/bin/pfctl
NATCONF=/var/tmp/pf.conf

touch ${PGETC}/rdr_main.conf
touch ${PGETC}/rdr_back.conf
touch ${PGETC}/tbl_main.conf
touch ${PGETC}/tbl_back.conf
touch ${PGETC}/if_main.conf
touch ${PGETC}/if_back.conf

# The following tables are for multi-lines routing
echo "set limit states  120000" > ${NATCONF}
echo "set limit src-nodes  10000" >> ${NATCONF}
echo "set limit frags  5000" >> ${NATCONF}
echo "set limit tables  200" >> ${NATCONF}
echo "set limit table-entries  200000" >> ${NATCONF}
echo "set optimization aggressive" >> ${NATCONF}
echo "set skip on lo0" >> ${NATCONF}
echo "set state-policy floating" >> ${NATCONF}
echo "scrub in all random-id fragment reassemble" >> ${NATCONF}

echo "table <tbl_main> persist" >> ${NATCONF}
echo "table <tbl_back> persist" >> ${NATCONF}

bitnum=`${FLOWEYE} util bitnum ${ADMIN_MASK}`
network=`${FLOWEYE} util network ${ADMIN_IP} ${ADMIN_MASK}`

# NAT rules
if [ "${MAIN_RTPORT}" != "" ]; then
	echo "nat on ${MAIN_RTPORT} from ${network}/${bitnum} to any -> (${MAIN_RTPORT})" >> ${NATCONF}
fi

if [ "${BACK_RTPORT}" != "" ]; then
	echo "nat on ${BACK_RTPORT} from ${network}/${bitnum} to any -> (${BACK_RTPORT})" >> ${NATCONF}
fi

# RDR rules
if [ "${MAIN_RTPORT}" != "" ]; then
	exec 0<${PGETC}/rdr_main.conf
	while read proto port inip inport; do
		cmdstr="rdr on ${MAIN_RTPORT} proto ${proto} from any to (${MAIN_RTPORT}) port ${port}"
		cmdstr="${cmdstr} -> ${inip} port ${inport}"
		echo "${cmdstr}" >> ${NATCONF}
	done
fi

if [ "${BACK_RTPORT}" != "" ]; then
	exec 0<${PGETC}/rdr_back.conf
	while read proto port inip inport; do
		cmdstr="rdr on ${BACK_RTPORT} proto ${proto} from any to (${BACK_RTPORT}) port ${port}"
		cmdstr="${cmdstr} -> ${inip} port ${inport}"
		echo "${cmdstr}" >> ${NATCONF}
	done
fi

# Route rules
echo "pass in all" >> ${NATCONF}
echo "pass out all" >> ${NATCONF} 
echo "pass in quick on ${ADMIN_PORT} from ${network}/${bitnum} to ${ADMIN_PORT}" >> ${NATCONF}
. ${PGETC}/if_back.conf
if [ "${BACK_RTPORT}" != "" -a "${if_gateway}" != "" ]; then
	cmdstr="pass in quick on ${BACK_RTPORT} reply-to (${BACK_RTPORT} ${if_gateway})"
	cmdstr="${cmdstr} from any  to any keep state"
	echo "${cmdstr}" >> ${NATCONF}

	cmdstr="pass in quick on ${ADMIN_PORT} route-to (${BACK_RTPORT} ${if_gateway})"
	cmdstr="${cmdstr} from any to <tbl_back>" 
	echo "${cmdstr}" >> ${NATCONF}
fi 

# Default routing policy
if_gateway=""
. ${PGETC}/if_main.conf
if [ "${MAIN_RTPORT}" != "" -a "${if_gateway}" != "" ]; then
	cmdstr="pass in quick on ${ADMIN_PORT} route-to (${MAIN_RTPORT} ${if_gateway})"
	cmdstr="${cmdstr} from any to any"
	echo "${cmdstr}" >> ${NATCONF}
fi

