#!/bin/sh -e
# sign.command
# By Chris Pepper, 2006-2008
# Usage: sign.command CSR | sign.command
# Example: sign.command www.reppep.com.20071108.csr

# CA host (if network accessible -- not necessarily a good idea)
CAHOST=ca.reppep.com
# CA path
CAPATH=/Volumes/ca.reppep.com
# CA certificate
CACERT=$CAPATH/ca.reppep.com.20070616.crt


if [[ $# = 0 ]]
 then
  echo -n "Please enter the CSR's filename, which must end in '.csr': "
  read CSR
  CERT=`dirname $CSR`/`basename $CSR .csr`
 else
  CERT=`dirname $1`/`basename $1 .csr`
fi

if [[ ! -r $CACERT ]]
 then
  echo "$0: ERROR: root cert ($CACERT) not readable"
  exit 1
fi

if [[ ! -r ${CERT}.csr ]]
 then
  echo "$0: ERROR: ${CERT}.csr not readable"
  exit 1
fi


# Sign it!
openssl ca -in $CERT.csr -out $CERT.crt
# If you get a bogus CSR vs. CA mismatch, add " -policy policy_anything" to the above command.

# Append CA cert to the new signed cert, to facilitate installation of the CA cert.
echo >> $CERT.crt
echo >> $CERT.crt
cat $CACERT >> $CERT.crt

echo "Your signed certificate is:"
ls -l $CERT.crt


# Think carefully before enabling the section below. For a medium to high security CA, the files should not be on a network accessible computer. If you are running a low-security CA, however, the lines below can make usage more convenient.
# 
# FIXME! This should be a conditional on CAHOST being non-blank.
# 
# # Facilitate extraction of certs from $CAHOST, if accessible:
# echo
# echo "To download the cert, first cd to a safe place on your workstation. Then fetch the signed certificate from $CAHOST:"
# echo "scp root@$CAHOST:$PWD/$CERT.crt ./"