#!/usr/bin/env bash

# Provides: check_enddate_certificate

TMP=$(mktemp /tmp/tmp.XXXXXXXXXX)

die () {
    echo "PASSIVE-CHECK:check_enddate_certificate;$1;$2"
    rm "${TMP}"
    exit 0
}

DIR="/dev/shm/certs"
test -d "${DIR}" || die 0 "There is no dir ${DIR}"

certs_list="$DIR/allCAs*.pem"
test -z "${certs_list}" && die 0 "There are no certs for check"

WARNING=14
COUNT=0
NOWDATE=$(date +%s)

for i in ${certs_list}; do
    if [ -e "${i}" ]; then
        ENDDATE=$(openssl x509 -in "${i}" -noout -enddate | cut -d = -f 2 | xargs -0 date +%s -d)
        EXPIRE=$(echo "($ENDDATE - $NOWDATE)/(60*60*24)" | bc)
        if [ "$EXPIRE" -le "$WARNING" ]; then
            COUNT=$(( COUNT+1 ))
            echo -n "${i##*/} - $EXPIRE; " >> "${TMP}"
        fi
    else
        continue
    fi
done

if [ "$COUNT" -ne "0" ]; then
    die 2 "Certificates expire: $(cat "${TMP}")"
else
    die 0 "All certificates are up-to-date"
fi
