#!/bin/sh
BASE=$1
if [ -z "$1" ]; then
echo "Usage: $0 canonical_name [alias1] [alias2] [...]"
exit 0
fi
if [ -n "$2" ]; then
echo '[extensions]' > alternate.cnf
echo "$@" |fmt -w 1 | sed -e 's/^/DNS:/g' -e 's/$/,/g'|xargs echo 'subjectAltName=' | sed -e 's/ //g' -e 's/,$//g'>> alternate.cnf
fi
echo "passphrase?"
read PASSPHRASE
echo "$PASSPHRASE" > ${BASE}.passphrase
export PASSPHRASE
openssl req -config ./openssl-conf.cnf -passout "env:PASSPHRASE" -new -utf8 > ${BASE}.csr
openssl rsa -passin "env:PASSPHRASE" -in privkey.pem -out ${BASE}.key
mv privkey.pem ${BASE}.pkey
if [ -f "./alternate.cnf" ]; then EXTENSIONS="-extfile ${BASE}.cnf -extensions extensions"; mv alternate.cnf ${BASE}.cnf;fi
openssl x509 -in ${BASE}.csr -out ${BASE}.crt -req -signkey ${BASE}.key -days 2000 $EXTENSIONS
cp ${BASE}.key ${BASE}.pem
echo "">> ${BASE}.pem
cat ${BASE}.crt >> ${BASE}.pem

echo "${BASE}.passphrase is the passphrase of your certificate. VERY PRIVATE"
echo "${BASE}.csr is the initial request of your certificate. PUBLIC"
if [ -f "${BASE}.cnf" ]; then
echo "${BASE}.cnf is the extension section of your certificate. PUBLIC"
fi
echo "${BASE}.key is the unprotected key of your certificate. PRIVATE"
echo "${BASE}.pkey is the protected key of your certificate. PRIVATE"
echo "${BASE}.crt is the certificate itself. PUBLIC"
echo "${BASE}.pem is the combined certificate/unprotected key. PRIVATE"

