#!/bin/sh
PATH=/sbin:/usr/sbin:/bin:/usr/bin

cd /etc/sysconfig/network-scripts
. network-functions

IPSECADM=/usr/sbin/ipsecadm
IP=/sbin/ip

CONFIG=$1
[ -f "$CONFIG" ] || CONFIG="ifcfg-$1"
source_config

if [ -z "$TUNLOCAL" ]; then
 echo "missing TUNLOCAL"
 exit 1
fi

if [ -z "$TUNREMOTE" ]; then
 echo "missing TUNREMOTE"
 exit 1
fi

if [ -z "$PHYSLOCAL" ]; then
 echo "missing PHYSLOCAL"
 exit 1
fi

if [ -z "$PHYSREMOTE" ]; then
 echo "missing PHYSREMOTE"
 exit 1
fi

if [ -z "$SPI" ]; then
 echo "missing SPI"
 exit 1
fi

if [ -z "$CIPHER" ]; then
 echo "missing CIPHER"
 exit 1
fi

if [ -z "$CIPHERFILE" ]; then
 echo "missing CIPHERFILE"
 exit 1
fi

if [ "$2" = "boot" -a "$ONBOOT" = "no" ]; then
  exit
fi

[ -x "$IP" ] || {
 echo "$IP does not exist or is not executable"
 echo "ifup-ipsectun for $DEVICE exiting"
 logger -p daemon.info -t ifup-ipsectun "$IP does not exist or is not executable for $DEVICE"
 exit 1
}

[ -x "$IPSECADM" ] || {
 echo "$IPSECADM does not exist or is not executable"
 echo "ifup-ipsectun for $DEVICE exiting"
 logger -p daemon.info -t ifup-ipsectun "$IPSECADM does not exist or is not executable for $DEVICE"
 exit 1
}

modprobe cryptoapi
# find a module for the cipher
CIPHERMODULE=`echo cipher-$CIPHER|sed 's/-...$//'`
if ! modprobe $CIPHERMODULE; then
		echo "Error probing $CIPHERMODULE";
		exit 1;
fi
modprobe ipsec_tunnel && \
$IPSECADM sa add --spi=$SPI --src=$PHYSLOCAL --dst=$PHYSREMOTE --cipher=$CIPHER \
--cipher-keyfile=/etc/ipsec/$CIPHERFILE --duplex && \
$IPSECADM tunnel add $DEVICE --local=$PHYSLOCAL --remote=$PHYSREMOTE && \
$IP address add $TUNLOCAL peer $TUNREMOTE dev $DEVICE && \
$IP link set dev $DEVICE up && \
exec /etc/sysconfig/network-scripts/ifup-post "ifcfg-$DEVICE" "$2"
