#! /bin/sh
#
# Convert X.509 PEM files for (self-signed) certificates to a dual-blob
# format that includes the bespoke BEGIN TRUSTED CERTIFICATE blob set to
# trust the certiicate for all purposes
# This may allevite RHEL9 issues around incorrect trust for self-signed 
# certificates that are alrady designatured as explicitly trusted in 
# the X509_CERT_DIR but are processed like subordinate/end-entity certs
#
# @(#)$Id$
#

help() {
  cat <<EOF
Usage: $0 pem-cert-file [pem-cert-file ...]

Convert X.509 PEM files for (self-signed) certificates to a dual-blob
format that includes the bespoke BEGIN TRUSTED CERTIFICATE blob set to
trust the certiicate for all purposes
This may allevite RHEL9 issues around incorrect trust for self-signed 
certificates that are alrady designatured as explicitly trusted in 
the X509_CERT_DIR but are processed like subordinate/end-entity certs.

EOF
}

while [ $# -gt 0 ]
do
  case "$1" in 
  -h | --help ) help ; exit 0 ;;
  -* ) echo "Unknown option $1, exiting" >&2 ; exit 1 ;;
  *  ) break ;;
  esac
done

[ $# -gt 0 ] || help && exit 0

for cafile in "$@"
do
  # test if this is indeed a self-signed root
  #
  if [ ! -f "$cafile" ]; then
    echo "Cannot read $cafile - not a file?" >&2
    continue
  fi
  sub=`openssl x509 -subject -noout -in "$cafile" 2>/dev/null | sed -e 's/^[^=]*=//'`
  iss=`openssl x509 -issuer -noout -in "$cafile" 2>/dev/null | sed -e 's/^[^=]*=//'`

  if [ -z "$sub" -o -z "$iss" ]; then
    echo "Cannot extract subject or issuer from $cafile - ignoring file" >&2
    continue
  fi

  if [ "$sub" != "$iss" ]; then
    echo "Not a self-signed certificate - ignoring $cafile"
    continue
  fi

  echo "Processing $cafile ..."

  # did we already do this one?
  BTCC=`grep -c "BEGIN TRUSTED CERTIFICATE" "$cafile"`
  if [ $BTCC -ne 0 ]; then
    echo "... already a trusted blob in $cafile - ignoring file"
    continue
  fi

  tempblob=`mktemp --tmpdir certblob.XXXXXX`
  openssl x509 -in "$cafile" \
    -trustout \
    -addtrust clientAuth -addtrust serverAuth -addtrust emailProtection \
    > "$tempblob"
  cat "$cafile" >> "$tempblob"

  # is this indeed the expected file?
  BTCC=`grep -c "BEGIN TRUSTED CERTIFICATE" "$tempblob"`
  BCC=`grep -c "BEGIN CERTIFICATE" "$tempblob"`

  if [ $BTCC -ne 1 -o $BCC -ne 1 ]; then
    echo "Blob $tempblob is NOT A COMBINED TRUST FILE - bailing" >&2
    exit 1
  fi

  # now re-write the original file
  cat "$tempblob" > "$cafile"
  echo "... done"
done

