#!/bin/bash
#
# ptudor@ptudor.net
#
# Generates private key, cert request, and signs the request

dir=/usr/local/ptudorCA
tmp=/tmp
umask 077

if [ "$1" = "" ]
  then
  echo "  This script requires an argument of the name of the server"
  echo "  this certificate is for. Try again."
  exit 99
fi

mkdir $1
perl -pi -e "s/%%servername/$1/g" $dir/openssl.cnf
echo -e "\nIf you screwed up the hostname, DO NOT press ^c. Finish then revoke it."         
echo -e "\n\nFirst we generate the certificate request and private key:\n\n"
openssl req -nodes -new -x509 -keyout $dir/$1/$1-key.pem -out $dir/$1/$1-key.pem -days 1461 -config $dir/openssl.cnf
echo -e "\n\nNow we sign it with our root CA\n\n"
openssl x509 -x509toreq -in $dir/$1/$1-key.pem -signkey $dir/$1/$1-key.pem -out $tmp/tmp.pem
openssl ca -config $dir/openssl.cnf -policy policy_anything -out $dir/$1/$1-cert.pem -infiles $tmp/tmp.pem
rm -f $tmp/tmp.pem
perl -pi -e "s/$1/%%servername/g" $dir/openssl.cnf

