#!/bin/bash

host=$1
port=$2

cert=$(echo | openssl s_client -connect "$host":"$port" -servername "$host" 2>/dev/null | openssl x509)
issuer_hash=$(echo "$cert" | openssl x509 -noout -issuer_hash)
not_after=$(echo "$cert" | openssl x509 -noout -dates | grep '^notAfter=')

if [[ -z "$cert" ]] || [[ -z "$issuer_hash" ]] || [[ -z "$not_after" ]]
then
    echo "UNKNOWN - Could not retrieve certificate! [$host:$port]"
    exit 3
fi

warn_days=60
crit_days=30

case "$issuer_hash" in
    # 4f06f81d: issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
    # 8d33f237: issuer=C = US, O = Let's Encrypt, CN = R3
    4f06f81d|8d33f237)
        warn_days=10
        crit_days=3
        ;;
esac

if ! echo "$cert" | openssl x509 -noout -checkend 0 >/dev/null 2>&1
then
    echo "CRITICAL - Certificate has expired! [$host:$port] [$not_after]"
    exit 2
elif ! echo "$cert" | openssl x509 -noout -checkend $((86400 * crit_days)) >/dev/null 2>&1
then
    echo "CRITICAL - Certificate will expire really soon: [$host:$port] [$not_after]"
    exit 2
elif ! echo "$cert" | openssl x509 -noout -checkend $((86400 * warn_days)) >/dev/null 2>&1
then
    echo "WARNING - Certificate will expire soon: [$host:$port] [$not_after]"
    exit 1
fi

echo "OK - [$host:$port] [$not_after]"
exit 0
