#!/bin/bash
#
# Creates the truststore file by combining the stock cacerts file from Java
# along with all truststore.d/*.key files.  Each key is imported with an alias
# equal to the filename without the ".key" extension.
#
# Arguments:
# $1 - The truststore file to create
#
# AO Industries, Inc.
# support@aoindustries.com
#
set -o errexit
set -o nounset

. /opt/jdk-lts/profile.sh

if [ -z "${1:-}" ]
then
   echo "Usage: ${0} /path/to/truststore" 1>&2
   exit 64 # EX_USAGE in /usr/include/sysexits.h
fi

TRUSTSTORE="${1}"
echo "TRUSTSTORE=${TRUSTSTORE}"

if [ ! -d "${TRUSTSTORE}.d" ]
then
    echo "Not a directory: ${TRUSTSTORE}.d" 1>&2
    exit 20 # ENOTDIR in /usr/include/asm-generic/errno-base.h
fi

JDK="$(dirname "$(dirname "$(readlink -e "$(which java)")")")"
echo "JDK=${JDK}"

# Start with stock cacerts file
cp "${JDK}/lib/security/cacerts" "${TRUSTSTORE}.new"

# Import and trust additional keys
for KEY in "${TRUSTSTORE}.d"/*.key
do
    if [ "${KEY}" != "${TRUSTSTORE}.d/*.key" ]
    then
        echo "${KEY}"
        ALIAS="$(echo "${KEY}" | sed -rn 's|^.*/(.+)\.key$|\1|p')"
        echo -n "    ${ALIAS} - "
        keytool -importcert \
            -alias "${ALIAS}" \
            -file "${KEY}" \
            -noprompt \
            -trustcacerts \
            -keystore "${TRUSTSTORE}.new" \
            -storepass changeit
    fi
done

# Overwrite in-place to preserve permissions
cat "${TRUSTSTORE}.new" > "${TRUSTSTORE}"
rm -f "${TRUSTSTORE}.new"
