#! /bin/bash

# keygen.sh - generate CA and/or host keys
#
#    Copyright (C) 2000-2002 Tommi Virtanen <tv@debian.org>
#    Copyright (C) 2003 Kai Henningsen <kai@debian.org>
#
#    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.
#
#    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; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

umask 077

cfg=$1
shift
if [ -z "$cfg" ]
then
	echo "Need a cfg template"
	exit 1
fi

caname=$1
shift
if [ -z "$caname" ]
then
	echo "Need a CA name"
	exit 1
fi
casafename=` echo -n $caname | tr -c 0-9a-zA-Z. _ `

name=$1
shift
if [ -z "$name" ]
then
	echo "Need a host name"
	exit 1
fi
safename=` echo -n $name | tr -c 0-9a-zA-Z _ `
ca=keys/ca

mkdir -p $ca
chmod 755 $ca
[ -e $ca/index.txt ] || touch $ca/index.txt
[ -e $ca/serial ] || echo 01 > $ca/serial

cakey=$ca/$casafename.key
cacert=$ca/$casafename.crt

req_name="$caname"
export req_name ca
[ -e $cakey -a -e $cacert ] || openssl req -days 3650 -nodes -new -x509 -keyout $cakey -out $cacert -config $cfg

chmod 644 $cacert

hostkeydir=keys/host

mkdir -p $hostkeydir
chmod 700 $hostkeydir

if [ "$name" == "CA only" ]
then
	exit
fi

key=$hostkeydir/$safename.key
csr=$hostkeydir/$safename.csr

req_name="$name"
[ -e $key -a -e $csr ] || openssl req -days 3650 -nodes -new -keyout $key -out $csr -config $cfg

crt=$hostkeydir/$safename.crt

[ -e $csr -a ! -e crt ] && openssl ca -batch -days 3650 -name CA_default -in $csr -out $crt -cert $cacert  -keyfile $cakey -md sha1 -policy policy_match -outdir $ca -config $cfg

