#!/bin/bash
# Compares letsencrypt live and renew
STATE_OK="0"
STATE_WARNING="1"
STATE_CRITICAL="2"
STATE_UNKNOWN="255"

#
# Typical nagios exit function
# @param 1 Error code
# @param 2 Message
#
function nagios_exit () {
    echo "$2"
    exit "$1"
}

#
# Nagios OK Exit
# @param 1 Message
#
function nagios_ok () {
    nagios_exit $STATE_OK "$@"
}

#
# Nagios WARNING Exit
# @param 1 Message
#
function nagios_warn () {
    nagios_exit $STATE_WARNING "$@"
}

#
# Nagios CRITICAL Exit
# @param 1 Message
#
function nagios_crit () {
    nagios_exit $STATE_CRITICAL "$@"
}

#
# Nagios UNKNOWN Exit
# @param 1 Message
#
function nagios_unknown () {
    nagios_exit $STATE_UNKNOWN "$@"
}

#######
# Logic

RES_CODE=0
RES_MSG=""

# It should get the list of directories in live and renewal
LIVE_LIST=$(find /etc/letsencrypt/live/ -mindepth 1 -maxdepth 1 \( -type d -or -type l \) -printf "%f.conf\n"|sort)
RENEW_LIST=$(find /etc/letsencrypt/renewal/ -maxdepth 1 -type f -printf "%f\n"|sort)

# It should get compare the lists
MISSING_LIVE=$(for f in $LIVE_LIST ; do [[ $RENEW_LIST =~ $f ]] || echo $f; done)
MISSING_RENEW=$(for f in $RENEW_LIST ; do [[ $LIVE_LIST =~ $f ]] || echo $f; done)

# It should get the RES_CODE
if [ -n "$MISSING_LIVE" ] || [ -n "$MISSING_RENEW" ] ; then
    RES_CODE=$STATE_CRITICAL
    RES_MSG="Missing in live: '`echo $MISSING_LIVE|sed 's/.conf//'`' / Missing Renew: '$MISSING_RENEW'"
fi

# It should return
case $RES_CODE in
    0)
        nagios_ok "OK."
    ;;
    1)
        nagios_warn "$RES_MSG"
    ;;
    2)
        nagios_crit "$RES_MSG"
    ;;
    *)
        nagios_unknown "UNKNOWN. No idea what is happening."
    ;;
esac
