#!/bin/sh
# -----------------------------------------------------------------------------
# Script for generating certificates using keytool and openssl.
# -----------------------------------------------------------------------------
    FQDN="OU=Unit,O=Organization,L=City,S=State,C=US"
USERNAME=$1

if [ -z "$USERNAME" ] ; then
  echo "You must supply username as argument"
  exit 0
fi

echo "1. Generate Tomcat's certificate..."
keytool -genkeypair -keyalg RSA -dname "CN=Tomcat,${FQDN}"      -alias tomcat                        -keystore server.jks      -storepass changeit -keypass changeit

echo "2. Generate the client's certificate..."
keytool -genkeypair -keyalg RSA -dname "CN=${USERNAME},${FQDN}" -alias ${USERNAME} -storetype pkcs12 -keystore ${USERNAME}.p12 -storepass changeit -keypass changeit

echo "3. Export the client's certificate as PKCS12..."
keytool -exportcert                  -file ${USERNAME}.crt      -alias ${USERNAME} -storetype pkcs12 -keystore ${USERNAME}.p12 -storepass changeit

echo "4. Import the client's certificate as a CA..."
keytool -importcert -v -trustcacerts -file ${USERNAME}.crt      -alias ${USERNAME}                   -keystore server.jks      -storepass changeit                   -noprompt

echo "5. Validate the client's certificate..."
keytool -list       -v                                                                               -keystore server.jks      -storepass changeit

echo "6. Validate the client's certificate..."
openssl pkcs12 -info                 -in ${USERNAME}.p12                                                                       -password pass:changeit -passout pass:changeit
