#! /bin/sh
#
# generate new key for this host
#
# Copyright (C) 2001, 2002  Henry Spencer.
# Copyright (C) 2014 Paul Wouters <pwouters@redhat.com>
# Copyright (C) 2014 Tuomo Soini <tis@foobar.fi>
#
# 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 of the License, or (at your
# option) any later version.  See <http://www.fsf.org/copyleft/gpl.txt>.
#
# 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.
#

me="ipsec newhostkey"
usage="Usage: $me [--output filename] [--seeddev device] [--bits n] \\
    [--quiet] [--hostname host] [--configdir nssdbdir] [--password password] "

bits=
verbose=
host=
seeddev="--seeddev /dev/random"
output="/etc/ipsec.secrets"
configdir="/etc/ipsec.d"
password=
for dummy; do
    case "$1" in
	--bits)
	    bits="${2}"
	    shift
	    ;;
	--quiet)
	    verbose=
	    ;;
	--hostname)
	    host="--hostname ${2}"
	    shift
	    ;;
	--output)
	    output="${2}"
	    shift
	    ;;
	--verbose)
	    verbose="--verbose"
	    ;;
	--version)
	    echo "$me $IPSEC_VERSION"
	    exit 0
	    ;;
	--random)
	    echo "$me warning: --random is obsoleted, using --seeddev"
	    seeddev="--seeddev ${2}"
	    shift
	    ;;
	--seeddev)
	    seeddev="--seeddev ${2}"
	    shift
	    ;;
	--configdir)
	    configdir="${2}"
	    shift
	    ;;
	--password)
	    password="--password ${2}"
	    shift
	    ;;
	--help)
	    echo "$usage"
	    exit 0
	    ;;
	--)
	    shift
	    break
	    ;;
	-*)
	    echo "$me: unknown option \`$1'" >&2
	    exit 2
	    ;;
	*)
	    break
	    ;;
    esac
    shift
done

if [ -d "${output}" ]; then
    echo "ERROR: output file should be a secrets file, not a directory"
    exit 255
fi

if [ -s "${output}" ]; then
    echo "${0}: WARNING: file \"${output}\" exists, appending to it" >&2
fi

if [ ! -d ${configdir} ]; then
    echo "No such directory: ${configdir}"
    exit 255
fi

certutil -L -d sql:$configdir >/dev/null 2>/dev/null
RETVAL=$?
if [ ${RETVAL} -eq 255 ]; then
    echo "NSS database in $configdir not initialized."
    echo "    Please run 'ipsec initnss --configdir $configdir'"
    exit 255
fi

key=$(ipsec rsasigkey ${verbose} ${seeddev} --configdir sql:${configdir} ${password} ${host} ${bits})
RETVAL=$?
if [ ${RETVAL} -eq 0 ]; then
    umask 077
    TEMPFILE=$(/bin/mktemp ${output}.XXXXXXX)
    (
	echo ': RSA	{'
	echo "${key}"
	echo '	}'
	echo '# do not change the indenting of that "}"'
    ) > ${TEMPFILE}
    if [ -s "${output}" ]; then
	cat ${TEMPFILE} >> ${output}
	rm ${TEMPFILE}
    else
	mv ${TEMPFILE} ${output}
    fi
else
    exit ${RETVAL}
fi
