#!/bin/sh

# In case of disaster, uncomment the next line and watch the output
# set -x
#
# This script runs out of cron.  Tell it where to find Big Brother.
BBHOME=/home/bb/bb18b3
export BBHOME

TESTHOST=system.domain.com
URL="http://$TESTHOST/"
USERNAME=bbusername
PASSWORD=bbsecretword

# Where to stash the downloaded html files.  These get patched into the BB
# report so that the monitoring guys can click through and see what we got.
BBDIR="$BBHOME/www/siteminder"

# Gonna need a cookie jar.  Start off empty, so each checkout starts clean.
COOKIES="$BBDIR/$TESTHOST.cookies"
rm -f $COOKIES

# Some standard curl flags.  See the curl man page for details
STDOPTS="-w %{url_effective} -L --connect-timeout 60 --max-time 120 -s -S -b $COOKIES -c $COOKIES -A Mozilla/4.79"

# This is just a tag for identifying environment dumps.
BBPROG=bb-siteminder.sh; export BBPROG

# The next block came from the BB ext example script.  If BBHOME is not set
# there's no point continuing.  If BBTMP is not set, load up the standard
# environment from bbdef.sh.  
if test "$BBHOME" = ""
then
        echo "BBHOME is not set... exiting"
        exit 1
fi

if test ! "$BBTMP"                      # GET DEFINITIONS IF NEEDED
then
         # echo "*** LOADING BBDEF ***"
        . $BBHOME/etc/bbdef.sh          # INCLUDE STANDARD DEFINITIONS
fi

# This is used to label the result column
TEST="login"

# Make sure bail out code is set.
bailout=0

# ========== step 1 ==========
# Grab the first page
STEP=step1
# Name the file for the host, test and step, to make it unique
FILENAME=$BBDIR/$TESTHOST.$TEST.$STEP.html
# remove any previous copy to avoid misunderstandings
rm -f $FILENAME

# Grab the first page.  The effective url is recorded for patching
# into the action url is necessary
effect=`$CURL $STDOPTS \
  -o $FILENAME \
  $URL`
# Save the return code, it might be important
ret=$?

# code 52 means "the server sent nothing"
if [ "$ret" -eq "52" ]; then
  # empty reply, try it again
  MESSAGE="$STEP: failed with curl error code: 52 - Empty reply from server.  Url: <a href=$URL>$URL</a>"
  MESSAGE="$MESSAGE
$STEP: retrying..."
  sleep 2
  effect=`$CURL $STDOPTS \
    -o /dev/null \
    $URL`
  ret=$?
fi

if [ -s $FILENAME ]; then
  # file exists and has size greater than zero.  look for something to validate
  TESTSTR="Something from the Login Page"
  check=`$GREP -ic "$TESTSTR" $FILENAME`
  if [ "$check" -gt "0" ]; then
    # Found the test string, we're good to continue
    MESSAGE="$MESSAGE
$STEP: Got Login page - found <b>$TESTSTR</b>"
  else
    # Didn't find the test string, bail out of subsequent steps
    MESSAGE="$MESSAGE
$STEP: failed to find <b>$TESTSTR</b>.  curl error code: $ret.  Url: <a href=$URL>$URL</a>"
    bailout=1
  fi
else
  # Got nothing useful from the server, give up
  MESSAGE-"$MESSAGE
$STEP: failed with empty file.  curl error code: $ret.  Url: <a href=$URL>$URL</a>"
  bailout=1
fi

# If previous step completed OK, perform next step
if [ "$bailout" -eq "0" ]; then
  # formextract.pl strips out the form elements and formats them like this:
  #   -d username=
  #   -d password=
  #   http://server.domain.com/path/to/form/processor
  # On some pages, the action url is not fully qualified.
  FORM=`cat $FILENAME | $HOME/bin/formextract.pl`
  # Pull out the form variable lines and patch in the userid & password
  FORMVARS=`echo "$FORM" | $GREP -- '-d' | $SED \
    -e "s/txtUsername=/txtUsername=$USERNAME/" \
    -e "s/Password=/Password=$PASSWORD/"`
  # extract the action url.  Adjustments can be to the url in the pipeline
  ACTION=`echo "$FORM" | $TAIL -1`

  # Break up the effective url based on the /'s
  OFS="$IFS"
  IFS="/"
  set $effect
  IFS="$OFS"

  # Assemble the proper action url.  It should be one of these forms:
  # Complete URL:  http://system.domain.com/path/to/form/processor
  # URL="$ACTION"
  # Absolute path, no hostname: /path/to/form/processor
  # URL="$1//$3$ACTION"
  # Relative path, no hostname: path/to/form/processor
  # URL="$1//$3/$ACTION"
  # pick up $1 (protocol) & $3 (hostname), because the // in the effective url makes $2=null.
  URL="$1//$3$ACTION"

  STEP=step2
  FILENAME=$BBDIR/$TESTHOST.$TEST.$STEP.html
  rm -f $FILENAME

  # Post the form back to the action url.  The returned file should
  # contain the page a browser would show after logging in.
  effect=`$CURL $STDOPTS \
    -w "%{url_effective}" \
    -o $FILENAME \
    $FORMVARS \
    $URL`
  ret=$?

  # As before, make sure the file is not empty, and that it contains
  # something we recognise from a successful login.  You can also look
  # for signs of login failure, such as a repeat of the login page, or
  # some message such as "login failed".

  if [ -s $FILENAME ]; then
    if [ "$ret" -eq "0" ]; then
      TESTSTR="Big Brother Test Page"
      check=`$GREP -ic "$TESTSTR" $FILENAME`
      if [ "$check" -gt "0" ]; then
        MESSAGE="$MESSAGE
$STEP: Found <b>$TESTSTR</b>.  Looking good"
      fi
    else
      MESSAGE="$MESSAGE
$STEP: failed to find <b>$TESTSTR</b>.  curl error code: $ret.  Url: <a href=$URL>$URL</a>"
      bailout=1
    fi
  else
    MESSAGE-"$MESSAGE
$STEP: failed with empty file.  curl error code: $ret.  Url: <a href=$URL>$URL</a>"
    bailout=1
  fi
fi

# If bailout is non-zero, something unexpected happened.
if [ "$bailout" -eq "1" ]; then
  COLOR="red"
elif [ "$bailout" -eq "2" ]; then
  # This is useful for non-critical-but-interesting conditions
  # that may be worth looking for.  There are none in this example.
  COLOR="yellow"
else
  # WooHoo!!
  COLOR="green"
fi

MESSAGE="$MESSAGE
<P>
See the saved files in <a href=$BBWEBHOST/bb/siteminder/>the checkout directory</a>"
#

# The script runs from cron, with output directed to a file in /tmp.
# This echo is not strictly necessary, but it can be useful to validate
# that it ran correctly
echo "$TESTHOST: $TEST: $COLOR"

# convert the dots to commas in the hostname
MACHINE=`echo $TESTHOST | $SED -e 's/\./,/g'`

# Assemble the status message as per normal
LINE="status $MACHINE.$TEST $COLOR `date`
$MESSAGE"

# fire it off to BB/Hobbit
$BB $BBDISP "$LINE"                     # SEND IT TO BBDISPLAY
