#!/bin/bash

set -o nounset \
    -o errexit \
    -o verbose \
    -o xtrace

# Generate CA key
openssl req -new -x509 -keyout pluralsight-ca.key -out pluralsight-ca.crt -days 365 -subj '/CN=kafka.pluralsight.com/OU=PT/O=Pluralsight/L=Utah/S=UT/C=US' -passin pass:notsecret -passout pass:notsecret

for i in zookeeper-1 zookeeper-2 zookeeper-3 broker-1 broker-2 broker-3 connect schema-registry ksqldb-server kstreams
do
	echo $i
  keytool -keystore $i.keystore.jks \
            -alias $i \
            -genkey -keyalg RSA \
            -dname "CN=$i, OU=PT, O=Pluralsight, L=Utah, S=UT, C=US"\
            -storepass notsecret \
            -keypass notsecret

	# Create CSR, sign the key and import back into keystore
	keytool -keystore $i.keystore.jks -alias $i  -certreq -file $i.csr -sigalg SHA256withRSA -storepass notsecret -keypass notsecret

	openssl x509 -sha256 -req -CA pluralsight-ca.crt -CAkey pluralsight-ca.key -in $i.csr -out $i-ca-signed.crt -days 9999 -CAcreateserial -passin pass:notsecret

	keytool -keystore $i.keystore.jks -alias CARoot -import -file pluralsight-ca.crt -storepass notsecret -keypass notsecret

	keytool -keystore $i.keystore.jks -alias $i -import -file $i-ca-signed.crt -storepass notsecret -keypass notsecret

	# Create truststore and import the CA cert.
	keytool -keystore $i.truststore.jks -alias CARoot -import -file pluralsight-ca.crt -storepass notsecret -keypass notsecret

  rm $i.csr
  rm $i-ca-signed.crt
done