#!/usr/bin/env bash
# ==========================================================================
#         ____            _                     _____           _
#        / ___| _   _ ___| |_ ___ _ __ ___     |_   _|__   ___ | |___
#        \___ \| | | / __| __/ _ \ '_ ` _ \ _____| |/ _ \ / _ \| / __|
#         ___) | |_| \__ \ ||  __/ | | | | |_____| | (_) | (_) | \__ \
#        |____/ \__, |___/\__\___|_| |_| |_|     |_|\___/ \___/|_|___/
#               |___/
#                             --- System-Tools ---
#                  https://www.nntb.no/~dreibh/system-tools/
# ==========================================================================
#
# X.509 Certificate Viewer
# Copyright (C) 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

# Bash options:
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
