#!/bin/bash
# Copyright Rene Mayrhofer, 2001
# This shell script is distributed under the terms of the GNU General Public License.

printhelp() {
  echo "This utility is used to create a X509 private key and mathing "
  echo "certificate request and is also able to self-sign the request to "
  echo "create a certificate. The key, certificate request and certificate "
  echo "are created in a way that they are suitable for the usage with "
  echo "FreeS/WAN and will probably be insecure for other purposes."
  echo 
  echo "Beware: The created RSA private key is stored unencrypted so that "
  echo "FreeS/WAN can use it without asking for a password. Protect the key "
  echo "carefully and do not use it for other purposes !"
  echo
  echo "Usage: $0 <key length> <days> <key file> <cert> <self sign> <country code> "
  echo "          <state> <locality> <org.> <org. unit> <common name> <email>"
  echo
  echo "key length:      the length of the RSA key that will be created"
  echo "days:            the certificate will stay valid this number of days"
  echo "key file:        the filename of the created RSA private key"
  echo "cert:            when creating a self-signed certificate, the name of"
  echo "                 the created certificate file, otherwise the name of "
  echo "                 the created certificate request"
  echo "self sign:       true: create a self-signed certificate"
  echo "                 false: only create a certificate request"
  echo
  echo "The other fields will be placed in the certificate request."
}

if [ $# -ne 12 ]; then
    printhelp
    exit 1
fi

case $5 in
  false)
    certreq=$4.req
    selfsigned=""
    ;;
  true)
    certreq=$4
    selfsigned="-x509"
    ;;
  *)
    printhelp
    exit 1
    ;;
esac

echo -e "$6\n$7\n$8\n$9\n${10}\n${11}\n${12}\n\n\n" | \
  /usr/bin/openssl req -new -outform PEM -out $certreq \
                       -newkey rsa:$1 -nodes -keyout $3 -keyform PEM \
                       -days $2 $selfsigned >/dev/null
echo

exit 0

