#!/bin/sh

. /etc/PG.conf

# Configure interface
if_ipaddr=""
if_netmask=""
if_gateway=""
[ ! -e ${PGETC}/if_main.conf ] && touch ${PGETC}/if_main.conf
. ${PGETC}/if_main.conf
if [ "${if_ipaddr}" != "" -a "${if_netmask}" != "" ]; then
	ifconfig ${MAIN_RTPORT} ${if_ipaddr} netmask ${if_netmask}

	# Configure default gateway
	gateway=`netstat -rn | grep "^default" | awk '{print $2}' 2>/dev/null`
	if [ "${gateway}" != "${if_gateway}" ]; then
		ermsg=`route delete default 2>&1`
		route add default ${if_gateway} >/dev/null
		echo "Set default gateway to ${if_gateway}"
	fi
fi

# Backup interface
if [ "${BACK_RTPORT}" != "" ]; then
        if_ipaddr=""
        if_netmask=""
	[ ! -e ${PGETC}/if_back.conf ] && touch ${PGETC}/if_back.conf
        . ${PGETC}/if_back.conf

        if [ "${if_ipaddr}" != "" -a "${if_netmask}" != "" ]; then
                ifconfig ${BACK_RTPORT} ${if_ipaddr} netmask ${if_netmask}
        fi
fi

# Create configuration file /var/tmp/pf.conf
${PGPATH}/bin/natcfg

# Load nat kernel module
if [ "`kldstat | grep pf.ko`" = "" ]; then
        kldload ${PGPATH}/kernel/pf.ko
fi

# OK, load template configuration file
${PGPATH}/bin/pfctl -f /var/tmp/pf.conf

cat ${PGETC}/tbl_main.conf| ${PGPATH}/bin/pfctl -t tbl_main -Treplace -f- 2>/dev/null
cat ${PGETC}/tbl_back.conf| ${PGPATH}/bin/pfctl -t tbl_back -Treplace -f- 2>/dev/null

# Enable NAT module
${PGPATH}/bin/pfctl -e 2>/dev/null

# Turn on forwarding
sysctl net.inet.ip.forwarding=1

# ARP BINDING
if [ -f ${PGETC}/arp.txt ]; then
	exec 0<${PGETC}/arp.txt
	while read ipaddr macaddr theothers
	do
		errmsg=`arp -s ${ipaddr} ${macaddr} 2>&1`
	done
fi
