#!/bin/bash
###############################################
#
# Nagios plugin to check SSL Certivicat timeleft
#
# Copyright 2011 Simon Walther
#
# Version 1.0
# Created: 2011-11-11 (opensource@first-instance.de)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 3 of the License,
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
#
# This program comes with ABSOLUTELY NO WARRANTY.
#
###############################################

OPENSSL=openssl

STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3

usage()
{
	echo "Usage: `basename $0` -f /path/to/ssl.crt|pem [-w warndays] [-c criticaldays]"
	echo "  Options:"
	echo "  -f STRING  [/path/to/ssl.crt|pem]"
	echo "  -w INTEGER [default: $days_warn]"
	echo "  -c INTEGER [default: $days_crit]"
	echo
	exit 88
}

check_args()
{
	days_warn=10
	days_crit=4

	if [ $# -lt 2 ]; then
		usage
		exit 88
	fi

	while [ $# -gt 0 ]
	do
		case "$1" in
			-f)	shift
				sslfile=$1
			;;
			-w)	shift
				days_warn=$1
			;;
			-c)	shift
				days_crit=$1
			;;
			-?)	 usage
			;;
			-h*|-?) usage
			;;
			*)	 usage
				 exit 88
			;;
		esac
		shift
	done
}

main()
{
	check_args $*

	if [[ ! -f $sslfile ]]
	then
		echo "SSL UNKNOWN - File $sslfile not found."
		exit $STATE_UNKNOWN
	fi

	lefttime=`date +%s -d"\`$OPENSSL x509 -text -in $sslfile | grep "Not After" | awk -F' : ' '{print $2}'\`"`
	leftdays=`echo $[$lefttime/60/60/24]`

	x=`date +%s`
	x=`echo $[$x/60/60/24]`
	leftdays=`echo $[$leftdays-$x]`

	msg="$sslfile: $leftdays days remaining"
	if [[ `echo $leftdays` -lt `echo $days_crit` ]]
	then
		echo "SSL CRITICAL $msg"
		exit $STATE_CRITICAL
	fi
	if [[ `echo $leftdays` -lt `echo $days_warn` ]]
	then
		echo "SSL WARNING $msg"
		exit $STATE_WARNING
	fi

	echo "SSL OK $msg"
	exit $STATE_OK
}

main $*
exit 0