#!/bin/bash

set -e

[ -z "$KEYSTORE_CONF_DIR" ] && KEYSTORE_CONF_DIR=/home/forgerock
[ -z "$KEYSTORE_CONF" ] && KEYSTORE_CONF=$KEYSTORE_CONF_DIR/keystore.json
[ -z "$KEYSTORE_TYPE" ] && KEYSTORE_TYPE=$(jq -r .storeType $KEYSTORE_CONF)
[ -z "$KEYSTORE_DIR" ] && KEYSTORE_DIR=/keystore
[ -z "$KEYSTORE" ] && KEYSTORE=$KEYSTORE_DIR/keystore.$KEYSTORE_TYPE

[ -z "$SECRETS_DIR" ] && SECRETS_DIR=/var/run/secrets/keystore
[ -z "$STOREPASS_FILE" ] && STOREPASS_FILE=$SECRETS_DIR/.storepass
[ -z "$KEYPASS_FILE" ] && KEYPASS_FILE=$SECRETS_DIR/.keypass
[ -z "$DSPASS_FILE" ] && DSPASS_FILE=$SECRETS_DIR/dirmanager.pw

[ -z "$STOREPASS" ] && STOREPASS=$(cat $STOREPASS_FILE)
[ -z "$KEYPASS" ] && KEYPASS=$(cat $KEYPASS_FILE)
[ -z "$DSPASS" ] && DSPASS=$(cat $DSPASS_FILE)

[ -f "$KEYSTORE" ] && rm -f "$KEYSTORE"

# Initialize keystore with $STOREPASS
echo "Initializing keystore $KEYSTORE..."
echo "$STOREPASS" | keytool -importpass -alias configstorepwd -storetype $KEYSTORE_TYPE -storepass $STOREPASS -keystore $KEYSTORE

# Import DS password
echo "Importing DS password..."
echo "$DSPASS" | keytool -importpass -alias dsameuserpwd -storetype $KEYSTORE_TYPE -storepass $STOREPASS -keystore $KEYSTORE

aliases=$(jq -r .keytoolAliases[].name $KEYSTORE_CONF)
for alias in $aliases; do
    cmd=$(jq -r ".keytoolAliases[] | select(.name==\"$alias\") | .cmd" $KEYSTORE_CONF)
    case $cmd in
        genkeypair|genseckey)
            args=$(jq -r ".keytoolAliases[] | select(.name==\"$alias\") | .args[]" $KEYSTORE_CONF | sed -e ':a;N;s/\n/ /;ba')
            echo "Executing '$cmd' command for '$alias' alias..."
            keytool -$cmd -alias $alias $args -storepass "$STOREPASS" -keypass "$KEYPASS" -storetype $KEYSTORE_TYPE -keystore $KEYSTORE
            ;;
        *)
            echo "Unknown/unsupported command '$cmd' for '$alias' alias!"
            ;;
    esac
done

echo "Listing keystore entries..."
keytool -list -storepass "$STOREPASS" -storetype $KEYSTORE_TYPE -keystore $KEYSTORE

exit 0

