#!/bin/bash

install -d  /{etc,usr/share}/ca-certificates/trust-source/{anchors,blacklist}

# Directories used by update-ca-trust (aka "trust extract-compat")
install -d  /etc/{ssl/certs/java,ca-certificates/extracted}

# Compatibility link for OpenSSL using /etc/ssl as CAdir
# Used in preference to the individual links in /etc/ssl/certs
ln -sr "/etc/ca-certificates/extracted/tls-ca-bundle.pem" "/etc/ssl/cert.pem"

# Compatiblity link for legacy bundle
ln -sr "/etc/ca-certificates/extracted/tls-ca-bundle.pem" "/etc/ssl/certs/ca-certificates.crt"


# At this time, while this script is trivial, we ignore any parameters given.
# However, for backwards compatibility reasons, future versions of this script must
# support the syntax "update-ca-trust extract" trigger the generation of output
# files in $DEST.

DEST=/etc/ca-certificates/extracted

extract() {
  trust extract --overwrite "$@"
}

# The directory-format extractors remove all files in the target directory, but not directories or files therein
extract --format=pem-directory-hash   --filter=ca-anchors --purpose=server-auth  $DEST/cadir
extract --comment --format=pem-bundle --filter=ca-anchors --purpose=server-auth  $DEST/tls-ca-bundle.pem
extract --comment --format=pem-bundle --filter=ca-anchors --purpose=email        $DEST/email-ca-bundle.pem
extract --comment --format=pem-bundle --filter=ca-anchors --purpose=code-signing $DEST/objsign-ca-bundle.pem
extract --comment --format=openssl-bundle --filter=certificates $DEST/ca-bundle.trust.crt

# We don't want to have to remove everything from the certs directory but neither
# do we want to leave stale certs around, so symlink it all from somewhere else
for f in $DEST/cadir/*; do
  ln -fsr -t /etc/ssl/certs "$f"
done

# Now find and remove all broken symlinks
find -L /etc/ssl/certs -maxdepth 1 -type l -delete

# Java bundle
extract --format=java-cacerts --filter=ca-anchors --purpose=server-auth /etc/ssl/certs/java/cacerts