#!/bin/bash

# add ah (autentication) to tunnel
USEAH=0
# device to add ip address to
DEVICE=dummy0

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

# don't run multiple times
ip route show | egrep -q "^default.*src ${INTERNAL_ADDR4}" && exit 0

if egrep -q '^0\.0\.0\.0$' <<<$INTERNAL_ADDR4
then
  exit 0
fi

if ! egrep -q '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' <<<$INTERNAL_ADDR4
then
  exit 0
fi

# standard link
if ip route | egrep -q '^default via [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3} dev [^ ]+'
then
  read a b DEFAULT_GW d DEFAULT_GW_DEV rest <<<$(ip route show | grep ^default)
  ip addr add ${INTERNAL_ADDR4}/${INTERNAL_CIDR4} dev ${DEVICE}
  ip route delete default
  ip route add ${REMOTE_ADDR} via ${DEFAULT_GW} dev ${DEFAULT_GW_DEV}
  ip route add default via ${DEFAULT_GW} dev ${DEFAULT_GW_DEV} src ${INTERNAL_ADDR4}
# point to point link
elif ip route | egrep -q '^default dev [^ ]+'
then
  read a b DEFAULT_GW_DEV rest <<<$(ip route show | grep ^default)
  ip addr add ${INTERNAL_ADDR4}/${INTERNAL_CIDR4} dev ${DEVICE}
  ip route delete default
  ip route add ${REMOTE_ADDR} dev ${DEFAULT_GW_DEV}
  ip route add default dev ${DEFAULT_GW_DEV} src ${INTERNAL_ADDR4}
# no default gw
else
  exit 0
fi

if [ ${LOCAL_PORT} = "4500" -a ${REMOTE_PORT} = "4500" ]
then
  NATT=1
  LOCAL="${LOCAL_ADDR}[${LOCAL_PORT}]"
  REMOTE="${REMOTE_ADDR}[${REMOTE_PORT}]"
else
  NATT=0
  LOCAL="${LOCAL_ADDR}"
  REMOTE="${REMOTE_ADDR}"
fi
(
echo "spdadd ${INTERNAL_ADDR4}/32[any] 0.0.0.0/0[any] any -P out ipsec 
       esp/tunnel/${LOCAL}-${REMOTE}/require"
if [ $USEAH -eq 0 -o $NATT -eq 1 ]
then
  echo ";"
else
  echo "ah/tunnel/${LOCAL}-${REMOTE}/require;"
fi
echo "spdadd 0.0.0.0/0[any] ${INTERNAL_ADDR4}[any] any -P in ipsec 
       esp/tunnel/${REMOTE}-${LOCAL}/require"
if [ $USEAH -eq 0 -o $NATT -eq 1 ]
then
  echo ";"
else
echo "ah/tunnel/${REMOTE}-${LOCAL}/require;"
fi
)| setkey -c


tmpresolv=$(mktemp) || exit 0
dns=0
if [ "x${INTERNAL_DNS4_LIST}" != "x" ]
then
  dns=1
  for dnsserver in ${INTERNAL_DNS4_LIST}
  do
    echo "nameserver $dnsserver" >> "$tmpresolv"
  done
elif [ "x${INTERNAL_DNS4}" != "x" ]
then
  dns=1
  echo "nameserver ${INTERNAL_DNS4}" >> "$tmpresolv"
fi

if [ $dns -eq 1 ]
then
  if [ -x /sbin/resolvconf ]
  then
    /sbin/resolvconf -a $DEVICE < "$tmpresolv"
  else
    cp -a -- /etc/resolv.conf /etc/resolv.conf.preracoon
    cat "$tmpresolv" > /etc/resolv.conf
  fi
fi

rm -f -- "$tmpresolv"
