#!/bin/bash

# usage:
# check-ssl-file.sh [ -d days ] [ -D days ] -f /path/to/file
# default days: 14

CSF_DAYS=14
CSF_WARN_DAYS=""
CSF_FILE=""

usage()
{
cat <<EOF
usage: $0 options

This script checks ssl certificate file to prevent its expiring.

OPTIONS:
   -h      Show this message
   -d      days (critial event)
   -D      warning days (warning event)
   -f      certificate file
EOF
}

check_days()
{
    if ! $(echo "$1" | grep -q '^[0-9][0-9]*$'); then
	echo '2;Failed: wrong parameters -d or -D (must be integer)'
	exit 0
    fi
}

check_cert()
{
    if [ ! -f "$1" ]; then
	echo '2;Failed: no such certificate file'
	exit 0
    fi

    # -L -- follow symlinks
#    if [ "$(file -L -b $1)" != "PEM certificate" ]; then
#	echo '2;Failed: file is not a certificate'
#	exit 0
#    fi

    # expires in
    CSF_EXPIRE_HUMAN=$(openssl x509 -in "$1" -enddate | head -n1 | cut -d"=" -f2)
    CSF_EXPIRE=$(date -d "$CSF_EXPIRE_HUMAN" +%s)

    if [ $(date +%s) -ge $CSF_EXPIRE ]; then
	echo '2;Failed: already expired'
	exit 0
    fi
    # time before expire
    CSF_TBE=$(($CSF_EXPIRE - $(date +%s)))
    # days to seconds: 1 day = 24 hours = 86400 seconds

    if [ -z $CSF_WARN_DAYS ]; then
	if [ $CSF_TBE -le $((86400*$CSF_DAYS)) ]; then
	    echo "2;Failed: $(basename $1) expires less than $CSF_DAYS days (expire date: $CSF_EXPIRE_HUMAN)"
	    exit 0
	fi
    else
	if [ $CSF_TBE -le $((86400*$CSF_DAYS)) ]; then
	    echo "2;Failed: $(basename $1) expires less than $CSF_DAYS days (expire date: $CSF_EXPIRE_HUMAN)"
	    exit 0
	fi
	if [ $CSF_WARN_DAYS -le $CSF_DAYS ]; then
	    echo '1;Warning: warning days are lesser (equal) than critical days'
	    exit 0
	fi
	if [ $CSF_TBE -le $((86400*$CSF_WARN_DAYS)) ]; then
            echo "1;Warning: $(basename $1) expires less than $CSF_WARN_DAYS days (expire date: $CSF_EXPIRE_HUMAN)"
	    exit 0
        fi
    fi
}



while getopts "hd:D:f:" opt; do
    case $opt in
	d)
	    CSF_DAYS=$OPTARG
	    ;;
	D)
	    CSF_WARN_DAYS=$OPTARG
	    ;;
	f)
	    CSF_FILE=$OPTARG
	    ;;
	h)
	    usage
	    exit 0
	    ;;
	\?)
	    usage
	    exit 1
	    ;;
    esac
done


if [ -z $CSF_FILE ]; then
    echo '2;Failed: missing file certificate argument'
    exit 0
fi

check_days $CSF_DAYS
[ ! -z $CSF_WARN_DAYS ] && check_days $CSF_WARN_DAYS

check_cert $CSF_FILE

echo '0;OK'


exit 0

