#!/bin/bash
#
# Copyright (c) 2006 Michael Hoennig <michael@hostsharing.net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#	$Id$

function checkPEM()
{
	aPemExpirationDate=`openssl x509 -noout -text -in $1 2>/dev/null | grep 'Not After :' | cut -d':' -f2-`
	if [ -z "$aPemExpirationDate" ]; then
		echo "ERROR: cannot determine exiration date for $aHive:$1" >&2
	else

		aPemExpirationDate=`date -d"$aPemExpirationDate" +'%Y-%m-%d %H:%M'`
		nPemExpirationSecs=`date -d"$aPemExpirationDate" +%s`
		nTodaysSecs=`date +%s`
		nTomorrowsSecs=`date -d'today +1day' +%s`
		nNextWeeksSecs=`date -d'today +1week' +%s`
		nNextMonthsSecs=`date -d'today +1month' +%s`

		nTodaysDeltaSecs=`echo $nPemExpirationSecs-$nTodaysSecs | bc`
		nTomorrowsDeltaSecs=`echo $nPemExpirationSecs-$nTomorrowsSecs | bc`
		nNextWeeksDeltaSecs=`echo $nPemExpirationSecs-$nNextWeeksSecs | bc`
		nNextMonthsDeltaSecs=`echo $nPemExpirationSecs-$nNextMonthsSecs | bc`

		if [ "$nTodaysDeltaSecs" -le "0" ]; then
			echo "WARNING: $aHive:$1 expired on $aPemExpirationDate"
		elif [ "$nTomorrowsDeltaSecs" -le "0" ]; then
			echo "WARNING: $aHive:$1 expires on $aPemExpirationDate - less than 1day left"
		elif [ "$nNextWeeksDeltaSecs" -le "0" ]; then
			echo "WARNING: $aHive:$1 expires on $aPemExpirationDate - less than 1week left"
		elif [ "$nNextMonthsDeltaSecs" -le "0" ]; then
			echo "WARNING: $aHive:$1 expires on $aPemExpirationDate - less than 1month left"
		fi

	fi
}

export aHive=`hostname -s`
while [ -n "$1" ]; do
	checkPEM $1
	shift
done
