#!/bin/bash
#
# Example-script to show, how to create and sign a selfsigned certificate, that
# contains multiple DNS-entries (SAN-extension)
#
# Usage:
# ./gencert.sh CN [CA_PASSWORD [KEYSTORE_PASSWORD [VALIDITY]]]


. settings.conf

if [ -z "$1" ];
then
  echo "CN must not be empty!"
  echo "$0 CN [CA_PASSWORD [KEYSTORE_PASSWORD [VALIDITY]]]"
  exit;
fi

if [ -a $1.p12 ];
then
  echo "The keystore $1.jks already exists";
  exit;
fi


if [ -z "$2" ]
then
  CA_PASSWORD=$DEFAULT_PASSWORD
else
  CA_PASSWORD="$2"
fi

if [ -z "$3" ]
then
  KEYSTORE_PASSWORD=$DEFAULT_PASSWORD
else
  KEYSTORE_PASSWORD="$3"
fi

if [ -z "$4" ]
then
  VALIDITY=365
else
  VALIDITY="$4"
fi


echo "Creating keystore $1.jks with a certificate and a key-pair for CN $1"
keytool -keystore $1.p12 -storetype pkcs12 -alias $1 -validity $VALIDITY -genkey -storepass $KEYSTORE_PASSWORD -dname "CN=$1,OU=$OU,O=$O,L=$L,ST=$ST,C=$C"

echo "Creating a Certificate-Signing-Request for the generated certificate"
keytool -keystore $1.p12 -storetype pkcs12 -alias $1 -certreq -file cert-file -storepass $KEYSTORE_PASSWORD

echo "Signing the Certificate-Signing-Request and adding an additional DNS-entry for localhost"
openssl x509 -req -CA ca-cert -CAkey ca-key -in cert-file -out $1.pem -days $VALIDITY -CAcreateserial -passin pass:$CA_PASSWORD -extensions SAN -extfile <(printf "\n[SAN]\nsubjectAltName=DNS:$1,DNS:localhost")

echo "Importing the root-certificate for the CA into the keystore $1.jks"
keytool -keystore $1.p12 -storetype pkcs12 -alias ca-root -import -file ca-cert -storepass $KEYSTORE_PASSWORD -noprompt

echo "Importing the signed certificate for CN $1 into the keystore $1.jks"
keytool -keystore $1.p12 -storetype pkcs12 -alias $1 -import -file $1.pem -storepass $KEYSTORE_PASSWORD

echo "Removing obsolet files..."
rm -v cert-file
