#!/usr/bin/env sh
# File: read-cert-template.sh
# Location: blog exclusive
# Author: bgstack15
# SPDX-License-Identifier: GPL-3.0-only
# Startdate: 2024-05-16-5 10:23
# Title: Read cert template
# Purpose: read certificate and print cert tempalte name if discoverable
# History:
# Usage:
# Reference: see blog post
# Improve:
# Dependencies:
#    openssl, ldapsearch, ldap credential in read-cert-template.conf

# Load conf, RCT_LDAPSERVER RCT_LDAPBASE RCT_LDAPAUTH1 RCT_LDAPAUTH2
RCT_CONF="${RCT_CONF:-${HOME}/.config/read-cert-template.conf}"
test -f "${RCT_CONF}" && . "${RCT_CONF}"

# use RCT_IN env var or first parameter, or else standard input
RCT_IN="${RCT_IN:-${1}}"
RCT_IN="${RCT_IN:-/dev/stdin}"

if echo "${RCT_IN}" | grep -qE -e '^-$|^stdin$' ;
then
   _input="$( cat )"
else
   _input="$( cat "${RCT_IN}" )"
fi

oid="$( echo "${_input}" | openssl x509 -in /dev/stdin -noout -text -certopt no_header,no_version,no_serial,no_signame,no_validity,no_subject,no_issuer,no_pubkey,ext_parse | sed -n -r -e '/1.3.6.1.4.1.311.21.7/,+2p' | awk '/OBJECT/{print $NF}' | sed -r -e 's/^://;' )"
test -n "${VERBOSE}" && printf 'oid=%s\n' "${oid}" 1>&2
LDAPTLS_REQCERT=never ldapsearch -LLL -o ldif-wrap=9000 -H "${RCT_LDAPSERVER}" ${RCT_LDAPAUTHUNQUOTED} "${RCT_LDAPAUTHQUOTED}" -b "CN=Certificate Templates,CN=Public Key,CN=Services,CN=Configuration,${RCT_LDAPBASE}" "(msPKI-Cert-Template-OID=${oid})" CN | awk '$1~/cn:/{$1="";print;}' | sed -r -e 's/^ +| +$//g;'
