#!/bin/sh

#
# sa-up.sh local configuration for a new SA
#
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

case `uname -s` in
NetBSD)
	DEFAULT_GW=`netstat -finet -rn | awk '($1 == "default"){print $2; exit}'`
	;;
Linux)
	DEFAULT_GW=`netstat --inet -rn | awk '($1 == "0.0.0.0"){print $2; exit}'`
	;;
esac

echo $@
echo "LOCAL_ADDR = ${LOCAL_ADDR}"
echo "LOCAL_PORT = ${LOCAL_PORT}"
echo "REMOTE_ADDR = ${REMOTE_ADDR}"
echo "REMOTE_PORT = ${REMOTE_PORT}"
echo "DEFAULT_GW = ${DEFAULT_GW}"
echo "INTERNAL_ADDR4 = ${INTERNAL_ADDR4}"
echo "INTERNAL_NETMASK4 = ${INTERNAL_NETMASK4}"
echo "INTERNAL_DNS4 = ${INTERNAL_DNS4}"

echo ${INTERNAL_ADDR4} | grep '[0-9]' > /dev/null || exit 0
echo ${INTERNAL_NETMASK4} | grep '[0-9]' > /dev/null || exit 0
echo ${DEFAULT_GW} | grep '[0-9]' > /dev/null || exit 0

mv /etc/resolv.conf /etc/resolv.conf.bak
( umask 22; touch /etc/resolv.conf )
echo "# Generated by racoon on `date`" >> /etc/resolv.conf
echo "nameserver ${INTERNAL_DNS4}" >> /etc/resolv.conf

case `uname -s` in
NetBSD)
	if=`netstat -finet -rn|awk '($1 == "default"){print $7; exit}'`
	ifconfig ${if} alias ${INTERNAL_ADDR4} netmask ${INTERNAL_NETMASK4}
	route delete default
	route add default ${DEFAULT_GW} -ifa ${INTERNAL_ADDR4}
	route add ${REMOTE_ADDR} ${DEFAULT_GW}
	;;
Linux)
	if=`netstat --inet -rn|awk '($1 == "0.0.0.0"){print $8; exit}'`
	ifconfig ${if}:1 ${INTERNAL_ADDR4}      
	route delete default
	route add ${REMOTE_ADDR} gw ${DEFAULT_GW} dev ${if}
	route add default gw ${DEFAULT_GW} dev ${if}:1
	;;
esac

LOCAL="${LOCAL_ADDR}"
REMOTE="${REMOTE_ADDR}"
if [ "x${LOCAL_PORT}" != "x500" ]; then
	# NAT-T setup
	LOCAL="${LOCAL}[${LOCAL_PORT}]"
	REMOTE="${REMOTE}[${REMOTE_PORT}]"
fi


echo "
spdadd ${INTERNAL_ADDR4}/32[any] 0.0.0.0/0[any] any
       -P out ipsec esp/tunnel/${LOCAL}-${REMOTE}/require;
spdadd 0.0.0.0/0[any] ${INTERNAL_ADDR4}[any] any
       -P in ipsec esp/tunnel/${REMOTE}-${LOCAL}/require;
" | setkey -c

#
# XXX This is a workaround for Linux forward policies problem. 
# Someone familiar with forward policies please fix this properly.
#
case `uname -s` in
Linux)
	echo "
	spddelete 0.0.0.0/0[any] ${INTERNAL_ADDR4}[any] any
		-P fwd ipsec esp/tunnel/${REMOTE}-${LOCAL}/require;
	" | setkey -c
	;;
esac
