#!/usr/bin/env bash
set -Eeuo pipefail

if [[ $# -lt 1 ]]; then
  echo "Usage: $0 <cert.pem> [more.pem ...]" >&2
  exit 1
fi

for cert in "$@"; do
  if [[ ! -f $cert ]]; then
    echo "Missing file: $cert" >&2
    continue
  fi

  echo "File: $cert"

  # Subject / CN
  subject_line=$(openssl x509 -in "$cert" -noout -subject -nameopt RFC2253 2>/dev/null || true)
  cn=$(sed -n 's/^subject=.*CN=\([^,]*\).*$/\1/p' <<<"$subject_line")
  if [[ -n ${cn:-} ]]; then
    echo "Subject (CN): $cn"
  else
    echo "Subject: ${subject_line#subject=}"
  fi

  # Grab SAN block
  if sans_block=$(openssl x509 -in "$cert" -noout -ext subjectAltName 2>/dev/null | sed -n '/Subject Alternative Name/,$p' || true) &&
    grep -q 'Subject Alternative Name' <<<"$sans_block"; then
    :
  else
    sans_block=$(openssl x509 -in "$cert" -noout -text 2>/dev/null | awk '
      /Subject Alternative Name/ {print_flag=1; next}
      print_flag && /^ *X509v3/ {print_flag=0}
      print_flag
    ')
  fi

  echo "SANs:"
  if [[ -n ${sans_block//[[:space:]]/} ]]; then
    # Flatten, strip leading label, split by comma, trim, and drop any "<Type>:" prefix
    sans_line=$(echo "$sans_block" | tr '\n' ' ' |
      sed 's/^.*Subject Alternative Name:[[:space:]]*//' |
      sed 's/^ *//')

    awk -v RS= -v ORS='\n' '{
      gsub(/, */, "\n");                    # comma -> newline
      n=split($0, a, "\n");
      for (i=1;i<=n;i++){
        s=a[i];
        gsub(/^ +| +$/, "", s);             # trim
        gsub(/^[A-Za-z ]+:/, "", s);        # strip "DNS:", "IP Address:", "URI:", etc.
        if (s != "") printf("  - %s\n", s);
      }
    }' <<<"$sans_line"
  else
    echo "  (none found)"
  fi

  echo
done
