#!/bin/bash
set -o nounset
set -o errexit
set -e

# ======================================================================
# SCRIPT TO ENCRYPT PROPERTY VALUES TO BE USED IN PROPERTIES
# Do not edit this file.
# To use, run the script with the plaintext property as an argument.
# The encrypted property will be printed to the screen and needs to
# manually updated in the properties file.
# If you want to use a different encryption algorithm, pass it as a second argument.
# ======================================================================

if [ $# -eq 0 ]; then
    echo "Usage: $0 \"plaintext property\" [encryption algorithm (default: PBEWITHMD5ANDDES)]"
    echo "Available algorithms:"
    echo "    PBEWITHMD5ANDDES, PBEWithMD5AndTripleDES, PBEWithSHA1AndDESede, PBEWithHMACSHA512AndAES_256 (JDK11+)"
    exit 1
fi

readonly ALGORITHM=${2:-PBEWITHMD5ANDDES}

readonly SCRIPT_DIR="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"

readonly ENCRYPTION_LIBRARY="jasypt-1.9.3.jar"
readonly ENCRYPTION_CLASS="org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI"
readonly LEGACY_SEED="p%9y#k&yFm?"
readonly LONG_SEED="OgZALG0xYyIatdYwwT4Emt63YSC4AaUPm2zjAHd7IJaZNueVUx/McbDz4lJCDAazVtxGJwOBDokocYRLrxS3rbQ="

if [[ ${ALGORITHM} == *"AES"* ]]; then
    readonly command=(java -cp ${SCRIPT_DIR}/${ENCRYPTION_LIBRARY} ${ENCRYPTION_CLASS} \
        input=$1 algorithm=${ALGORITHM} verbose=false \
        password=${LONG_SEED} ivGeneratorClassName=org.jasypt.iv.RandomIvGenerator)
elif [[ ${ALGORITHM} == "PBEWITHMD5ANDDES" ]]; then
    readonly command=(java -cp ${SCRIPT_DIR}/${ENCRYPTION_LIBRARY} ${ENCRYPTION_CLASS} \
        input=$1 algorithm=${ALGORITHM} verbose=false \
        password=${LEGACY_SEED})
else
    readonly command=(java -cp ${SCRIPT_DIR}/${ENCRYPTION_LIBRARY} ${ENCRYPTION_CLASS} \
        input=$1 algorithm=${ALGORITHM} verbose=false \
        password=${LONG_SEED})
fi

readonly property=$("${command[@]}")

echo "The property was successfully encrypted."
echo "The full output below should be used as a new property value in the properties file."
echo
if [[ "$ALGORITHM" == "PBEWITHMD5ANDDES" ]]; then
    echo "ENC(${property})"
else
    echo "ENC_${ALGORITHM}(${property})"
fi
echo

exit 0
