own-pki/lib/expired-date.sh
2026-04-26 20:44:39 +02:00

55 lines
1.8 KiB
Bash

# check if run from script
[[ "${BASH_SOURCE[0]}" == "${0}" ]] && exit 1
#------------------------------------------------------------------------------
# this funtcion return the expireDate array with
# data daysLeft|cn|exp
expired_date(){
nbrDays=$1
# set tmp file
tmpFile=$(mktemp)
# set date now in timestamp Unix
# timesatmp Unix = number of seconds elapsed
# since January 1, 1970 at 00:00:00 UTC (called epoch)
now=$(date -u +%s)
# test expired cert
#today=$(date +%s)
#now=$((today + 7*24*60*60)) # today +7 days
# read file list
certList=()
# set - if no .crt → files=() (empty)
shopt -s nullglob
certList=($CERTS_PATH/*.crt)
shopt -u nullglob
if [ "${#certList[@]}" -gt "0" ]; then
for crtFile in "${certList[@]}"; do
# set data from certfificate
cn=$(openssl x509 -noout -subject -in $crtFile | cut -d"=" -f3)
expiration=$(openssl x509 -noout -in $crtFile -enddate | cut -d"=" -f2)
# convert in timestamp Unix
exp=$(date -u -d "$expiration" +%s)
diffSec=$((exp - now))
daysLeft=$(( (diffSec + 86399) / 86400 ))
# write in tmpfile valide cert
if [ "$exp" -ge "$now" ] && [ "$daysLeft" -le "$nbrDays" ]; then
echo "$daysLeft|$cn|$expiration" >> "$tmpFile"
fi
# write in tmpfile expired cert
if [ "$exp" -lt "$now" ]; then
echo "$daysLeft|$cn|$expiration" >> "$tmpFile"
fi
done
fi
# put the content tmpfile in sorted array
expireDate=()
while IFS='|' read -r daysLeft cn exp; do
expireDate+=("$daysLeft|$cn|$exp")
done < <(sort -n "$tmpFile")
# delete tmpfile
rm -rf tmpFile
}