#!/bin/sh
#
# ipsec-setkey         This script set and unset ipsec rules
#
# chkconfig: 345 8 91
# description: This script set and unset ipsec rules at statup time.
#
# config: /etc/ipsec.conf

. /etc/init.d/functions

IPSEC_CONFIG="/etc/ipsec.conf"

if [ ! -f $IPSEC_CONFIG ]; then
    exit 0
fi

function ipsec_start() {
    gprintf "Loading %s modules:" "ipsec"
    err=0
    modprobe esp4 2>&1 >/dev/null || err=1
    modprobe ah4 2>&1 > /dev/null || err=1
    modprobe ipcomp 2>&1 > /dev/null || err=1
    modprobe esp6 2>&1 > /dev/null || err=1
    modprobe ah6 2>&1 > /dev/null || err=1
    modprobe ipcomp6 2>&1 > /dev/null || err=1
    [ $err = 0 ] && success || failure
    echo
    gprintf "Starting %s:" "ipsec-setkey"
    touch /var/lock/subsys/ipsec-setkey
    /sbin/setkey -f $IPSEC_CONFIG && success || failure
    echo
}

function ipsec_stop() {
    gprintf "Stopping %s:" "ipsec-setkey"
    err=0
    /sbin/setkey -F || err=1
    /sbin/setkey -FP || err=1
    rm -f /var/lock/subsys/ipsec-setkey
    [ $err = 0 ] && success || failure
    echo
}

function ipsec_status() {
    # quite ugly, but ... well 
    /sbin/setkey -D
    /sbin/setkey -DP
    if [ -f /var/lock/subsys/ipsec-setkey ]; then
	gprintf "%s is active\n"  "Ipsec-setkey"
    else
	gprintf "%s is not active\n" "Ipsec-setkey"
    fi
}

case "$1" in
    start)
	ipsec_start
	;;
    stop)
	ipsec_stop
	;;
    restart|reload)
	ipsec_stop
	ipsec_start
	# if we have modified some rules, racoon must be restarted
	service racoon condrestart
	;;
    condrestart)
	if [ -f /var/lock/subsys/ipsec-setkey ]; then
	    ipsec_stop
	    ipsec_start
	fi
	;;
    status)
	ipsec_status
	;;
    *)
	gprintf "Usage: %s:\n" "$(basename $0) {start|stop|restart|status}"
	exit 1
	;;
esac

exit 0
