#!/bin/sh
# -*- sh-basic-offset: 2 -*-

set -e
set -u

##
# Handle command line
##

authority="ca";

usage ()
{
  program=$(basename "$0");

  if [ $# != 0 ]; then echo "$@"; echo ""; fi;

  echo "usage: ${program} [options] host_name";
  echo "";
  echo "  -h              Show this help";
  echo "  -a authority    Use given certificate authority [${authority}].";
}

while getopts 'ha:' option; do
  case "$option" in
    '?') usage; exit 64; ;;
    'h') usage; exit 0; ;;
    'a') authority="${OPTARG}"; ;;
  esac;
done;
shift $((${OPTIND} - 1));

if [ $# != 1 ]; then
  usage;
  exit 64;
fi;

host="$1";

##
# Do The Right Thing
##

if [ "${authority}" != "NONE" ]; then
  if [ ! -s "${authority}.key" ]; then
    echo "Not a certificate authority key: ${authority}.key";
    exit 1;
  fi;
  if [ ! -s "${authority}.crt" ]; then
      echo "Not a certificate authority certificate: ${authority}.crt";
      exit 1;
  fi;
fi;

newfile ()
{
  # New file is not readable and empty
  name="$1";
  rm -f "${name}";
  tmp="$(mktemp "${name}")";
  if [ "${tmp}" != "${name}" ]; then
    mv "${tmp}" "${name}";
  fi;
}

#
# FIXME:
#   Remove requirement that user type in a pass phrase here, which
#   we then simply strip out.
#
if [ ! -s "${host}.key" ]; then
  echo "Generating host key...";
  newfile "${host}.key.tmp";
  openssl genrsa -des3 -out "${host}.key.tmp" 1024;
  echo "";

  echo "Removing pass phrase from key...";
  newfile "${host}.key";
  openssl rsa -in "${host}.key.tmp" -out "${host}.key";
  rm "${host}.key.tmp";
  echo "";
else
  echo "Key for ${host} already exists.";
fi;

#
# FIXME:
#   Remove requirement that user type the common name, which we
#   already know ($hostname).
#
if [ ! -s "${host}.csr" ]; then
  echo "Generating certificate request...";
  newfile "${host}.csr";
  openssl req -new -key "${host}.key" -out "${host}.csr";
  echo "";
else
  echo "Certificate request for ${host} already exists.";
fi;

if [ "${authority}" != "NONE" ]; then
  if [ ! -s "${host}.crt" ]; then
    echo "Generating certificate...";
    openssl x509 -req -in "${host}.csr" -out "${host}.crt" -sha1 -days 3650 \
	-CA "${authority}.crt" -CAkey "${authority}.key" -CAcreateserial;
    chmod 644 "${host}.crt";
    echo "";
  else
    echo "Certificate for ${host} already exists.";
  fi;

  # Print the certificate
  openssl x509 -in "${host}.crt" -text -noout;
fi;
