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

VALIDITY=365
PASSWORD=confidential

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

echo "Creating keystore $1.jks with a certificate and a key-pair for CN $1"
keytool -keystore $1.jks -alias $1 -validity $VALIDITY -genkey -storepass $PASSWORD -keypass $PASSWORD -dname "CN=$1,OU=kafka,O=trion,L=MS,ST=NRW,C=DE"
echo "Creating a Certificate-Signing-Request for the generated certificate"
keytool -keystore $1.jks -alias $1 -certreq -file cert-file -storepass $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 cert-signed -days $VALIDITY -CAcreateserial -passin pass:$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.jks -alias CARoot -import -file ca-cert -storepass $PASSWORD -noprompt
echo "Importing the signed certificate for CN $1 into the keystore $1.jks"
keytool -keystore $1.jks -alias $1 -import -file cert-signed -storepass $PASSWORD
echo "Removing obsolet files..."
rm -v cert-file cert-signed


