#!/usr/bin/env bash
# ==========================================================================
#     _   _ _ ____            ____          _____
#    | | | (_)  _ \ ___ _ __ / ___|___  _ _|_   _| __ __ _  ___ ___ _ __
#    | |_| | | |_) / _ \ '__| |   / _ \| '_ \| || '__/ _` |/ __/ _ \ '__|
#    |  _  | |  __/  __/ |  | |__| (_) | | | | || | | (_| | (_|  __/ |
#    |_| |_|_|_|   \___|_|   \____\___/|_| |_|_||_|  \__,_|\___\___|_|
#
#       ---  High-Performance Connectivity Tracer (HiPerConTracer)  ---
#                 https://www.nntb.no/~dreibh/hipercontracer/
# ==========================================================================
#
# High-Performance Connectivity Tracer (HiPerConTracer)
# Copyright (C) 2015-2025 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: dreibh@simula.no

set -eu


# ###### Usage ##############################################################
usage () {
   echo >&2 "Usage: $0 [-h|--help] certificate [...]"
   exit 1
}


# ###### Main program #######################################################

# ====== Handle arguments ===================================================
GETOPT="$(PATH=/usr/local/bin:${PATH} which getopt)"
options="$(${GETOPT} -o h --long help -a -- "$@")"
# shellcheck disable=SC2181
if [[ $? -ne 0 ]]; then
   usage
fi

eval set -- "${options}"
while [ $# -gt 0 ] ; do
   case "$1" in
      -h | --help)
         usage
         # shift
         ;;
      --)
         shift
         break
         ;;
  esac
done
if [ $# -lt 1 ] ; then
   usage
fi

# ====== Check availability of tools ========================================
OPENSSL="$(which openssl || true)"
if [ "${OPENSSL}" == "" ] ; then
   echo >&2 "ERROR: Unable to find OpenSSL!"
   exit 1
fi

# ====== Check each certificate =============================================
while [ $# -gt 0 ] ; do

   # ====== Look for certificate ============================================
   CERT="$1"
   shift
   if [ ! -e "${CERT}" ] ; then
      echo >&2 "ERROR: Unable to find certificate file ${CERT}!"
      exit 1
   fi

   echo -e "\e[34mCertificate ${CERT}:\e[0m"
   "${OPENSSL}" x509 -in "${CERT}" -noout -subject -dates -ext subjectAltName,basicConstraints,keyUsage,extendedKeyUsage | (
      validityFrom="?"
      while read -r line ; do
         if [[ "${line}" =~ ^(subject=)(.*)$ ]] ; then
            subject="${BASH_REMATCH[2]}"
            echo -e "\e[33mSubject:  \e[35m${subject}\e[0m"
         elif [[ "${line}" =~ ^(notBefore=)(.*)$ ]] ; then
            validityFrom="${BASH_REMATCH[2]}"
         elif [[ "${line}" =~ ^(notAfter=)(.*)$ ]] ; then
            validityTo="${BASH_REMATCH[2]}"
            echo -e "\e[33mValidity: \e[36m${validityFrom} - ${validityTo}\e[0m"
         elif [[ "${line}" =~ ^([ \t]*)(X509v3 .*:)(.*)$ ]] ; then
            extension="${BASH_REMATCH[2]}"
            critical="${BASH_REMATCH[3]}"
            echo -en "\e[33m${extension}\e[32m${critical}\e[0m   "
         elif [ "${extension}" != "" ] && [[ "${line}" =~ ^([ \t]*)(.*)$ ]] ; then
            extension=""
            echo -e "\e[36m${BASH_REMATCH[2]}\e[0m"
         fi
      done
   )
   echo -en "\e[0m"

   echo -e "\e[33mHierarchy:\e[0m"
   "${OPENSSL}" crl2pkcs7 -nocrl -certfile "${CERT}" | \
      "${OPENSSL}" pkcs7 -print_certs -noout | (
         entry=0
         while read -r line ; do
            if [[ "${line}" =~ ^(subject=)(.*)$ ]] ; then
               subject="${BASH_REMATCH[2]}"
               entry=$((entry + 1))
               echo -en "\e[33m${entry}. "
               if [ ${entry} -eq 1 ] ; then
                  echo -e "\e[35m${subject}\e[0m"
               else
                  echo -e "\e[37m${subject}\e[0m"
               fi
            fi
         done
      )

done
