#!/bin/bash

# xymonnet is not able to handle a connection to a secure http site via
# a proxy.  This script addresses that problem, using curl to fetch the
# headers from the remote web server.  The verbose output is saved and
# relevant details are extracted to pass on to xymon in the form of an
# sslcert report.
#
# Ralph Mitchell  2012-05-25
#
# call from tasks.cfg like this:
#   chkhttps.sh  <hostname_to_report>  <url>
#
# e.g.
#   chkhttps.sh server.domain.com https://server.domain.com/index.html

export TESTHOST="$1"
export URL="$2"
export MACHINE=`echo $TESTHOST | sed -e 's/\./\,/g'`
export TEST="http"

export CURL=/usr/bin/curl

export COOKIES="$XYMONTMP/$TESTHOST.cookies"
export CURLOPTS="--capath /etc/pki/tls/certs -s -S -L -m 60 --write-out %{time_total}"
# add cookies in case they might be useful
export CURLOPTS="$CURLOPTS -b $COOKIES -c $COOKIES"

#=-=-=-=-=-=-=
export OUTFILE=$XYMONTMP/$TESTHOST.html
rm -f $OUTFILE

# grab the page, record the elapsed time
TIMETOTAL=`$CURL -v -I $CURLOPTS -o $OUTFILE "$URL" 2> $XYMONTMP/$TESTHOST.sslcert`
RET=$?
# try to discover if we're all good, might want to examine the page
if [ "$RET" -ne 0 ]; then
  COLOR="red"
else
  COLOR="green"
fi

# assemble status message...
MESSAGE="status $MACHINE.$TEST $COLOR `date`

&$COLOR $URL

`tail -n +3 $OUTFILE`

Seconds:  $TIMETOTAL"

# ... and post to xymon
$XYMON $XYMSRV "$MESSAGE"
echo "$TESTHOST: $TEST: $COLOR"

################################################################
# and now fake the sslcert output
TEST="sslcert"
COLOR="green"
CERTINFO="$XYMONTMP/$TESTHOST.sslcert"
EXPIRY=`grep 'expire date:' $CERTINFO | sed -e 's/^.*expire date: //'`
EXPIRESECS=`date --date="$EXPIRY" +%s`
SECSNOW=`date +%s`
EXPIREDAYS=`expr \( $EXPIRESECS - $SECSNOW \) / 60 / 60 / 24`
SUBJECT=`grep 'subject:' $CERTINFO | sed -e 's/^.*subject: /subject:/'`
ISSUER=`grep 'issuer:' $CERTINFO | sed -e 's/^.*issuer: /issuer:/'`
STARTDATE=`grep 'start date:' $CERTINFO | sed -e 's/^.*start/start/'`
EXPIREDATE=`grep 'expire date:' $CERTINFO | sed -e 's/^.*expire date: /expire date:/'`
#
if [ "$SUBJECT" -a "$STARTDATE" -a "$EXPIREDATE" ]; then
  COLOR=green
  # assemble status message...   NOTE: the MESSAGE spans multiple lines
  MESSAGE="status $MACHINE.$TEST $COLOR `date`

&$COLOR SSL certificate for $URL expires in $EXPIREDAYS days


Server certificate:
        $SUBJECT
        $ISSUER
        $STARTDATE
        $EXPIREDATE"
else
  COLOR=red
  # assemble status message...   NOTE: the MESSAGE spans multiple lines
  MESSAGE="status $MACHINE.$TEST $COLOR `date`

&$COLOR No SSL certificate information found.  SSL check failed"
fi

# ... and post to xymon
$XYMON $XYMSRV "$MESSAGE"

echo "$TESTHOST: $TEST: $COLOR"
exit 0

