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

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

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

ipsectun_set_extras()
{
	if [ -n "$MTU" ]; then
		ip link set dev "$DEVICE" mtu $MTU
	fi
	ip link set dev "$DEVICE" $(ip_link_flag promisc $PROMISC) \
	$(ip_link_flag allmulti $ALLMULTI) $(ip_link_flag multicast $MULTICAST)
}

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

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

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 [ -n "$DIGEST" -o -n "$DIGESTFILE" ]; then
	if [ -z "$DIGEST" -o -z "$DIGESTFILE" ]; then
		echo "DIGEST and DIGESTFILE must be defined simultaneously!"
		exit 1
	fi
	DIGEST_OPTIONS="--digest=$DIGEST --digest-keyfile=/etc/ipsec/$DIGESTFILE"
fi

if [ -n "$CIPHER" -o -n "$CIPHERFILE" ]; then
	if [ -z "$CIPHER" -o -z "$CIPHERFILE" ]; then
		echo "CIPHER and CIPHERFILE must be defined simultaneously!"
		exit 1
	fi
	CIPHER_OPTIONS="--cipher=$CIPHER --cipher-keyfile=/etc/ipsec/$CIPHERFILE"
fi

if [ -z "$CIPHER_OPTIONS" -a -z "$DIGEST_OPTIONS" ]; then
	echo "Cipher or digest must be defined"
	exit 1
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
}

# ipsec_tunnel guesses correct module names itself, so we don't have
# to find a module for the cipher and digest
modprobe cryptoapi || {
	echo "CryptoAPI module not found"
	exit 1
}

modprobe ipsec_tunnel || {
	echo "ipsec_tunnel module not found"
	exit 1
}
$IPSECADM sa add --spi=$SPI --src=$PHYSLOCAL --dst=$PHYSREMOTE \
$CIPHER_OPTIONS $DIGEST_OPTIONS --duplex && \
$IPSECADM tunnel add $DEVICE --local=$PHYSLOCAL --remote=$PHYSREMOTE --spi=$SPI && \
ipsectun_set_extras && \
$IP address add $TUNLOCAL peer $TUNREMOTE dev $DEVICE && \
$IP link set dev $DEVICE up && \
exec /etc/sysconfig/network-scripts/ifup-post "ifcfg-$DEVICE" "$2"
