#!/bin/sh
#
# --------------------------------------------------------------------------
# Copyright notice
# --------------------------------------------------------------------------
# Copyright: Rene Mayrhofer, Sep. 2002
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING.  If not, write to
# the Free Software Foundation, 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
# On Debian GNU/Linux systems, the complete text of the GNU General
# Public License can be found in `/usr/share/common-licenses/GPL'.
# --------------------------------------------------------------------------
#

set -e

check_private() {
	if grep -A 2 "$IPSEC_SECRETS_PATTERN_1" /etc/ipsec.secrets |
	  tail --lines=2 |
	  grep -A 1 "$IPSEC_SECRETS_PATTERN_2" |
	  tail --lines=1 |
	  grep "$IPSEC_SECRETS_PATTERN_3" >/dev/null; then
		cp /etc/ipsec.secrets /etc/ipsec.secrets.orig
		return 0
	else
            echo "/etc/ipsec.secrets already contains a RSA secret key."
	    echo "Not creating a new key. If you want it to be created,"
            echo "restore /etc/ipsec.secrets to distributed state first."
	    return 1
	fi
}

insert_private_key_filename() {
	umask 077 ; (
		sed "/$IPSEC_SECRETS_PATTERN_1/,\$d" /etc/ipsec.secrets
		echo ": RSA $1"
		sed "1,/$IPSEC_SECRETS_PATTERN_3/d" /etc/ipsec.secrets
	) > /etc/ipsec.secrets.tmp
	mv /etc/ipsec.secrets.tmp /etc/ipsec.secrets
}

IPSEC_SECRETS_PATTERN_1=': RSA	{'
IPSEC_SECRETS_PATTERN_2='\-\- not filled in because ipsec.secrets existed at build time \-\-'
IPSEC_SECRETS_PATTERN_3='	}'

if check_private; then
	echo -n "Generating new X.509 certificate for IPSec authentication ... "
	# create a new certificate
	host=`hostname`
	newkeyfile="/etc/ipsec.d/private/${host}Key.pem"
	newcertfile="/etc/ipsec.d/${host}.pem"
	keylength=2048
	selfsigned=true
	countrycode="AT"
	statename="Upper Austria"
	localityname="Steyr"
	orgname="Gibraltar"
	orgunit="Gibraltar development"
	commonname="Gibraltar"
	email="not specified"
	/usr/lib/ipsec/mkx509cert $keylength 1500 "$newkeyfile" "$newcertfile" "$selfsigned" "$countrycode" "$statename" "$localityname" "$orgname" "$orgunit" "$commonname" "$email" >/dev/null 2>&1
	if [ "$selfsigned" = "true" ]; then
		openssl x509 -in "$newcertfile" -outform DER -out /etc/x509cert.der
	fi
	chmod 0600 "$newkeyfile"
	umask 077
	insert_private_key_filename "$newkeyfile"
	echo "done"
fi

exit 0
