#!/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

if [ -x /sbin/resolvconf ]
then
  /sbin/resolvconf -d ${DEVICE}
else
  test -f /etc/resolv.conf.preracoon && mv -- /etc/resolv.conf.preracoon /etc/resolv.conf
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

setkey -D | egrep -A 1 "^${LOCAL_ADDR}(\[[0-9]+\])? ${REMOTE_ADDR}(\[[0-9]+\])?" \
  | sed -rn "s/^[[:space:]]+([^[:space:]]+).*spi=([^(]+)\(.*/delete ${LOCAL_ADDR} ${REMOTE_ADDR} \1 \2;/p" \
  | setkey -c

setkey -D | egrep -A 1 "^${REMOTE_ADDR}(\[[0-9]+\])? ${LOCAL_ADDR}(\[[0-9]+\])?" \
  | sed -rn "s/^[[:space:]]+([^[:space:]]+).*spi=([^(]+)\(.*/delete ${REMOTE_ADDR} ${LOCAL_ADDR} \1 \2;/p" \
  | setkey -c

(
echo "spddelete ${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 "spddelete 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


# 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 route delete default
  ip route delete ${REMOTE_ADDR} via ${DEFAULT_GW} dev ${DEFAULT_GW_DEV}
  ip addr del ${INTERNAL_ADDR4}/${INTERNAL_NETMASK4} dev ${DEVICE}
  ip route add default via ${DEFAULT_GW} dev ${DEFAULT_GW_DEV}
# 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 route delete default
  ip route delete ${REMOTE_ADDR} dev ${DEFAULT_GW_DEV}
  ip addr del ${INTERNAL_ADDR4}/${INTERNAL_NETMASK4} dev ${DEVICE}
  ip route add default dev ${DEFAULT_GW_DEV}
# no default gw
else
  ip addr del ${INTERNAL_ADDR4}/${INTERNAL_NETMASK4} dev ${DEVICE}
  exit 0
fi

read a b DEFAULT_GW d DEFAULT_GW_DEV rest <<<$(ip route show | grep ^default)
if ! egrep -q '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' <<<$DEFAULT_GW
then
  exit 0
fi

ip route delete default
ip route delete ${REMOTE_ADDR} via ${DEFAULT_GW} dev ${DEFAULT_GW_DEV}
ip addr del ${INTERNAL_ADDR4}/${INTERNAL_NETMASK4} dev ${DEVICE}
ip route add default via ${DEFAULT_GW} dev ${DEFAULT_GW_DEV}

