#!/usr/bin/env bash
#
# Copyright 2016-2017 Confluent Inc.
#

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

dub ensure KAFKA_SECRETS_DIR
dub ensure KAFKA_LOG4J_DIR
dub ensure KAFKA_CONFIG_DIR
dub ensure CAAS_POD_ID

if [ -e /mnt/sslcerts/fullchain.pem ] && [ -e /mnt/sslcerts/privkey.pem ]; then

openssl pkcs12 -export \
	-in /mnt/sslcerts/fullchain.pem \
	-inkey /mnt/sslcerts/privkey.pem \
	-out /tmp/pkcs.p12 \
	-name kafkassl \
	-passout pass:mykeypassword

keytool -importkeystore \
	-deststorepass mystorepassword \
	-destkeypass mykeypassword \
	-destkeystore /tmp/keystore.jks \
	-srckeystore /tmp/pkcs.p12 \
	-srcstoretype PKCS12 \
	-srcstorepass mykeypassword 

fi

if [ -e /mnt/sslcerts/spec.json ]; then
  export KEYSTORE_LOCATION=/mnt/sslcerts/`jq -r .ssl_keystore_filename /mnt/sslcerts/spec.json`
  export KEYSTORE_TYPE=`jq -r .ssl_certificate_encoding /mnt/sslcerts/spec.json`
else
  echo "WARNING: /mnt/sslcerts/spec.json was not present, defaulting to /mnt/sslcerts/pkcs.p12"
  export KEYSTORE_LOCATION=/mnt/sslcerts/pkcs.p12
  export KEYSTORE_TYPE=PKCS12
fi

dub ensure KEYSTORE_LOCATION
dub ensure KEYSTORE_TYPE
echo "Keystore env vars: KEYSTORE_LOCATION=$KEYSTORE_LOCATION, KEYSTORE_TYPE=$KEYSTORE_TYPE"

SERVER_PROPS_FILE="${KAFKA_CONFIG_DIR}/kafka.properties"
if [ -f "${SERVER_PROPS_FILE}" ]; then
	echo "Server properties file was already generated (by init container): ${SERVER_PROPS_FILE}"
else
	echo "Server properties file was not yet created...generating it: ${SERVER_PROPS_FILE}"
	cat ${KAFKA_CONFIG_DIR}/shared/server-common.properties > "${SERVER_PROPS_FILE}"
	cat ${KAFKA_CONFIG_DIR}/pod/${CAAS_POD_ID}/server-pod.properties >> "${SERVER_PROPS_FILE}"
fi

sed -i -e 's@${KEYSTORE_LOCATION}@'"$KEYSTORE_LOCATION"'@' -e 's@${KEYSTORE_TYPE}@'"$KEYSTORE_TYPE"'@' ${SERVER_PROPS_FILE}
rc=$?; if [[ $rc != 0 ]]; then echo "sed failed for KEYSTORE_LOCATION and KEYSTORE_TYPE"; exit $rc; fi

# TODO - final configs need to go in a writable scratch directory
cat ${KAFKA_CONFIG_DIR}/shared/log4j.properties >  /opt/caas/config/kafka/log4j.properties
cat ${KAFKA_CONFIG_DIR}/pod/${CAAS_POD_ID}/log4j.properties >> /opt/caas/config/kafka/log4j.properties
cat ${KAFKA_CONFIG_DIR}/shared/disk-usage-agent.properties >  /opt/caas/config/kafka/disk-usage-agent.properties
cat ${KAFKA_CONFIG_DIR}/shared/jvm.config > /opt/caas/config/kafka/jvm.config
cat ${KAFKA_CONFIG_DIR}/pod/${CAAS_POD_ID}/jvm.config >> /opt/caas/config/kafka/jvm.config
cp /opt/caas/templates/jmx-exporter.yaml.j2 /opt/caas/config/jmx-exporter.yaml
cp /opt/caas/templates/otel-javaagent.properties /opt/caas/config/otel-javaagent.properties
