#!/bin/bash
#
# test_certexpire
#
# Ablaufdatum von Zertifikatsdateien an ULS
#
##################################################
#
unset SETULSHOSTNAME DT TMP_PATH S days
while getopts d:DT:h:S? op; do
  case "$op" in
   d) TMP_PATH="-d $OPTARG";;
   T) DT="$OPTARG";;
   D) days=1;;
   h) SETULSHOSTNAME="$OPTARG";;
   S) S="-S";;
   ?) echo "usage: $(basename $0) [-d storepath] [-S] [-D] [-T <datetime>] [-h <hostname>] <section> <teststep> <certpath> [...]"
      exit 0;;
  esac
done
shift $(( $OPTIND - 1 ))
#
if [[ $# -lt 3 ]]; then
  echo "usage: $(basename $0) [-d storepath] [-S] [-D] [-T <datetime>] [-h <hostname>] <section> <teststep> <certpath> [...]"
  exit 1
fi
#
if [[ -f /etc/uls/uls.conf ]]; then
  . /etc/uls/uls.conf
fi
if [[ -z "$DOMAINHOSTNAME" ]]; then
  DOMAINHOSTNAME="DOMAIN:`hostname -s`"
fi
if [[ -z "$ULSHOSTNAME" ]]; then
  ULSHOSTNAME=`hostname -s`
fi
#
if [[ -z "$DT" ]]; then
  DT=`date '+%F %T%:z'`
fi
#
ulssection="$1"
ulsteststep="$2"
{ echo "D;$DT;${SETULSHOSTNAME:-$ULSHOSTNAME};"
  shift 2
  while [[ -n "$1" ]]; do
    if [[ "$1" == *.txt ]]; then
      EXP=$(sed -n 's/\r//;s/^expiredate=//p' "$1")
      fsect=$(sed -n 's/\r//;s/^section=//p' "$1")
      ftst=$(sed -n 's/\r//;s/^teststep=//p' "$1")
      ffn=$(sed -n 's/\r//;s|^crt=.*/||p' "$1")
    elif [[ "$1" == *.crt || "$1" == *.pem ]] || grep -q 'BEGIN CERTIFICATE' "$1"; then
      notafter=$(openssl x509 -enddate -noout -in "$1" | sed -n 's/notAfter=//p')
      if [[ -n "$notafter" ]]; then
        EXP=$(date -d "$notafter" '+%F %T')
      else
        unset EXP
      fi
      unset fsect ftst ffn
    elif [[ "$1" == *.p7b ]]; then
      notafter=$(openssl pkcs7 -inform DER -print_certs -in "$1" | openssl x509 -enddate -noout | sed -n 's/notAfter=//p')
      if [[ -n "$notafter" ]]; then
        EXP=$(date -d "$notafter" '+%F %T')
      else
        unset EXP
      fi
      unset fsect ftst ffn
    else
      unset EXP
    fi
    if [[ -n "$EXP" ]]; then
      FN=${ffn:-$(basename "$1")}
      echo "V;;;${fsect:-$ulssection};${ftst:-$ulsteststep};${FN%.*};$EXP;{DT};"
      if [[ -n "$days" ]]; then
        expdays=$(( ($(date -d "$EXP" '+%s') - $(date '+%s')) / 86400 ))
        echo "V;;;;;;$expdays;days;"
      fi
    fi
    shift
  done
} | send_test_tab $TMP_PATH $S
