#!/bin/sh
set -e

# Import CA certificates from /certs/ca.pem into JVM truststore if present.
# This allows the server to trust custom CAs (e.g., Traefik self-signed in dev,
# or an internal PKI in production) for OIDC discovery and token exchange.
if [ -f /certs/ca.pem ]; then
    TRUSTSTORE="$JAVA_HOME/lib/security/cacerts"
    STOREPASS="changeit"
    TMPDIR=$(mktemp -d)

    # Split PEM bundle into individual certificates
    awk -v dir="$TMPDIR" '
        /-----BEGIN CERTIFICATE-----/ { n++ }
        n > 0 { print > dir "/cert-" n ".pem" }
    ' /certs/ca.pem

    count=0
    for cert in "$TMPDIR"/cert-*.pem; do
        [ -f "$cert" ] || continue
        if keytool -importcert -noprompt -trustcacerts \
            -alias "custom-ca-$count" \
            -file "$cert" \
            -keystore "$TRUSTSTORE" \
            -storepass "$STOREPASS" 2>/dev/null; then
            count=$((count + 1))
        fi
    done

    rm -rf "$TMPDIR"
    [ "$count" -gt 0 ] && echo "Imported $count CA certificate(s) into JVM truststore"
fi

exec java -Duser.timezone=UTC -jar /app/server.jar
