#!/bin/bash
# Generates a self-signed certificate.
# This script is derived from mkcert.sh from the mod_ssl distribution
#
# ::maintainer::
# ::copy::
#
CMD=`basename $0`
ssldir=${SSLDIR-/etc/ssl}

usage()
{
	echo "usage: $CMD [--days days] configname" >&2
}

[ x"$1" == x"--days" ] && {
	shift
	echo "$1" | grep -q '^[0-9][0-9]*$' || usage
	[ $1 -lt 365 ] && {
		echo "days should be at least 365" >&2
		exit 1
	}
	days=$1
	shift
}

# defaults
#
name=${1-`uname -n | sed -e 's/\..*//'`}
days=${days:-::ssl.duration::}

config=$name.cnf
certfile=$ssldir/certs/$name.pem
keyfile=$ssldir/private/$name.key



# sanity checks
#
[ -f $config ] || {
	echo "
		config file $config not found
		copy and edit 'example.cnf' to create one
	" >&2
	exit 1
}

for dir in $ssldir/certs $ssldir/private
do
	[ -d $dir -a -w $dir ] || {
		echo "directory '$dir' not exists or not writeable" >&2
		exit 1
	}
done

for file in $certfile $keyfile
do
	[ -f $file ] && {
		echo "can't overwrite existing file '$file', remove first" >&2
		exit 1
	}
done

openssl req -new -x509 -nodes -config $config -days $days \
	-sha256 \
	-out $certfile -keyout $keyfile || exit $?
chmod 0600 $keyfile
echo 
openssl x509 -subject -fingerprint -sha256 -noout -in $certfile || exit $?

exit 0
