#!/bin/bash
#
# test_web_single
#
# Test Websites
#
# usage: test_web_single [-h hostname] [-d storepath] [-S]
#                        <conf> [<date> <time>]
#
########################################################################
#
#
D=""
S=""
H="`hostname`"
#
while getopts d:h:S op
 do
  case "$op" in
    d) D="-d $OPTARG";;
    h) H="$OPTARG";;
    S) S="-S";;
    *) echo "usage: $0 [-h hostname] [-d storepath] <conf> [<date> <time> [<TZ>]]"
       exit 1;;
  esac
done
shift $(( $OPTIND - 1 ))
#
#
f="$1"
shift
if [[ $# -lt 2 ]]
 then
  DT="`date '+%F %T%:z'`"
else
  DT="$1 $2"
fi
#
TMPFILE=/tmp/test_web.$$.dat
MIN=`date --date="$DT" '+%M' | sed 's/^0//'`
STD=`date --date="$DT" '+%H' | sed 's/^0//'`
#
BASESECS=`date '+%s'`
#
if [[ -f "$f" ]]
 then
  parallel=`awk -F '[ \t]*=' 'BEGIN{w=1};$1=="parallel"{gsub("parallel[ \t]*=[ \t]*","",$0);w=$0};END{print 0+w}' "$f"`
  retry=`awk -F '[ \t]*=' '$1=="retry"{gsub("retry[ \t]*=[ \t]*","",$0);w=$0};END{print 1+w}' "$f"`
  retrywait=`awk -F '[ \t]*=' 'BEGIN{w=1};$1=="retrywait"{gsub("retrywait[ \t]*=[ \t]*","",$0);w=$0};END{print 0+w}' "$f"`
  hostname=`awk -F '[ \t]*=' '$1=="hostname"{gsub("hostname[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  section=`awk -F '[ \t]*=' '$1=="section"{gsub("section[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  teststep=`awk -F '[ \t]*=' '$1=="teststep"{gsub("teststep[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  detail=`awk -F '[ \t]*=' '$1=="detail"{gsub("detail[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  if [[ -n "$detail" ]]
   then
    detail="$detail "
  fi
  typ=`awk -F '[ \t]*=' '$1=="typ"{gsub("typ[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  url=`awk -F '[ \t]*=' '$1=="url"{gsub("url[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  proxy=`awk -F '[ \t]*=' '$1=="proxy"{gsub("proxy[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  timeout=`awk -F '[ \t]*=' '$1=="timeout"{gsub("timeout[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  storefile=`awk -F '[ \t]*=' '$1=="storefile"{gsub("storefile[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  minutes=`awk -F '[ \t]*=' '$1=="minutes"{gsub("minutes[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  hours=`awk -F '[ \t]*=' '$1=="hours"{gsub("hours[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  postct=`awk -F '[ \t]*=' '$1=="postct"{gsub("postct[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  postdata=`awk -F '[ \t]*=' '$1=="postdata"{gsub("postdata[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  followredirect=`awk -F '[ \t]*=' '$1=="followredirect"{gsub("followredirect[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  httpreturncode=`awk -F '[ \t]*=' '$1=="httpreturncode"{gsub("httpreturncode[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  getcertinfo=`awk -F '[ \t]*=' '$1=="getcertinfo"{gsub("getcertinfo[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  testhost=`awk -F '[ \t]*=' '$1=="testhost"{gsub("testhost[ \t]*=[ \t]*","",$0);w=$0};END{print !!w}' "$f"`
  regcount=`awk -F '[ \t]*=' '$1=="regcount"{gsub("regcount[ \t]*=[ \t]*","",$0);w=$0};END{print w}' "$f"`
  #
  if [[ -n "$hours" ]]
   then
    if ! echo "$hours" | awk -v TEST="$STD" -F ',' '
{ for( i=1; i<=NF; i++)
  { if( 1 < split($i, a, "/") )
    { p = a[1]
      if( a[2] > 1 )
        s = a[2]
      else
        s = 24
      t = 1
    }
    else
    { p = $i
      s = 1
      t = 0
    }
    if( 1 < split(p ,b ,"-") )
    { v = b[1]
      w = b[2]
    }
    else if( p == "*" )
    { v = 0
      w = 23
    }
    else
    { v = p
      if( t )
        w = 23
      else
        w = p
    }
    for( j = v; j <= w; j += s )
    { if( TEST == j )
        r = 1
    }
  }
}
END { if( r != 1 )
        exit(1)
    }'
     then
      exit 0
    fi
  fi
  if [[ -n "$minutes" ]]
   then
    if ! echo "$minutes" | awk -v TEST="$MIN" -F ',' '
{ for( i=1; i<=NF; i++)
  { if( 1 < split($i, a, "/") )
    { p = a[1]
      if( a[2] > 1 )
        s = a[2]
      else
        s = 60
      t = 1
    }
    else
    { p = $i
      s = 1
      t = 0
    }
    if( 1 < split(p ,b ,"-") )
    { v = b[1]
      w = b[2]
    }
    else if( p == "*" )
    { v = 0
      w = 59
    }
    else
    { v = p
      if( t )
        w = 59
      else
        w = p
    }
    for( j = v; j <= w; j += s )
    { if( TEST == j )
        r = 1
    }
  }
}
END { if( r != 1 )
        exit(1)
    }'
     then
      exit 0
    fi
  fi
  #
  if [[ -n "$section" && -n "$teststep" && -n "$typ" && -n "$url" && "${url#http://}" != "${url#https://}" ]]
   then
    if [[ -z "$postct" ]]
     then
      PCT=""
    else
      PCT="-C $postct"
    fi
    if [[ -z "$postdata" ]]
     then
      PDAT=""
    else
      PDAT="-d $postdata"
    fi
    if [[ -n "$followredirect" ]]
     then
      L="-L"
    else
      L=""
    fi
    if [[ -n "$httpreturncode" ]]
     then
      HRC="-D $TMPFILE.header"
    else
      HRC=""
    fi
    if [[ -n "$getcertinfo"  && "$url" == https://* ]]
     then
      VERBOSE="-v" 
      ERRFILE="$TMPFILE.stderr"
    else
      VERBOSE=""
      ERRFILE="/dev/null"
    fi
    while [[ $retry -gt 0 ]]
     do
      if [[ $parallel -gt 1 ]]
       then
        STT=`date '+%s%N'`
        for (( i = 1; $i < $parallel; i = $i +1 ))
         do
          curl -k -m ${timeout:-10} -o $TMPFILE$i -x "$proxy" "$url" 2>/dev/null &
        done
        curl $VERBOSE $HRC $L -k -m ${timeout:-10} -o $TMPFILE -x "$proxy" "$url" 2>$ERRFILE
        RET=$?
        wait
        ENT=`date '+%s%N'`
      else
        STT=`date '+%s%N'`
        curl $VERBOSE $HRC $L -k -m ${timeout:-10} -o $TMPFILE -x "$proxy" "$url" 2>$ERRFILE
        RET=$?
        ENT=`date '+%s%N'`
      fi
      if [[ $RET = 0 ]]
       then
        retry=0
        TD=$(( ($ENT - $STT)/1000000 ))
        SIZE=`stat -c "%s" $TMPFILE`
        F=`file -b $TMPFILE`
        case "$typ" in
          I) if [[ "${F#*image}" = "$F" ]]
              then
               SIZE=0
             fi;;
          X) if [[ "$F" = "${F#*XML}" ]]
              then
               SIZE=0
             fi;;
          H) if  [[ "$F" = "${F#*HTML}" ]]
              then
               SIZE=0
             fi;;
        esac
        send_test_value $D $S -h "${hostname:-$H}" "$section" "$teststep" "${detail}Size" $DT "$SIZE" "Byte"
        send_test_value $D $S -h "${hostname:-$H}" "$section" "$teststep" "${detail}Response Time" $DT "$TD" "ms"
        send_test_value $D $S -h "${hostname:-$H}" "$section" "$teststep" "${detail}Error" $DT "$RET" "#"
        if [[ "$testhost" = "1" ]]
         then
          send_test_value $D $S -h "${hostname:-$H}" "$section" "$teststep" "${detail}Testhost" $DT "`hostname`" '{}'
        fi
        if [[ -n "$regcount" ]]
         then
          RC=$(egrep -c "$regcount" $TMPFILE)
          send_test_value $D $S -h "${hostname:-$H}" "$section" "$teststep" "${detail}Test-Reg" $DT "$RC" "#"
        fi
        if [[ -n "$storefile" ]]
         then
          TMPDIR=/tmp/test_webdir.$$
          mkdir $TMPDIR
          mv $TMPFILE $TMPDIR/$storefile
          if [[ "$typ" == "I" ]]
           then
            send_image_value $D $S -h "${hostname:-$H}" "$section" "$teststep" "${detail}Image" $DT $TMPDIR/$storefile
          else
            send_file_value $D $S -h "${hostname:-$H}" "$section" "$teststep" "${detail}File" $DT $TMPDIR/$storefile
          fi
          rm -r $TMPDIR
        fi
        if [[ -n "$httpreturncode" ]]
         then
          RC="`awk '$1 ~ "^HTTP" {rc= $2};END{print rc}' $TMPFILE.header`"
          send_test_value $D $S -h "${hostname:-$H}" "$section" "$teststep" "${detail}HTTP-Return-Code" $DT "$RC" "#"
        fi
        if [[ -n "$getcertinfo"  && "$url" == https://* ]]
         then
          DATE=`fgrep -i 'expire date' $ERRFILE | head -1 | sed 's/.*e: //'`
          if [[ -n "$DATE" ]]
           then
            EXPIREDATE=$(date -d "$DATE" '+%F %T')
            EXPIREDAYS=$(( ($(date -d "$DATE" '+%s') - $(date '+%s')) / 86400 ))
            send_test_value $D $S -h "${hostname:-$H}" "$section" "$teststep" "${detail}Certexpiredate" $DT "$EXPIREDATE" "{DT}"
            send_test_value $D $S -h "${hostname:-$H}" "$section" "$teststep" "${detail}Certexpiredays" $DT "$EXPIREDAYS" "d"
          fi
        fi
      else
        send_test_value $D $S -h "${hostname:-$H}" "$section" "$teststep" "${detail}Error" $DT "$RET" "#"
        if [[ -n "$httpreturncode" ]]
         then
          RC="`awk '$1 ~ "^HTTP" {rc= $2};END{print rc}' $TMPFILE.header`"
          send_test_value $D $S -h "${hostname:-$H}" "$section" "$teststep" "${detail}HTTP-Return-Code" $DT "$RC" "#"
        fi
        retry=$(( $retry - 1 ))
        BASESECS=$(( $BASESECS + $retrywait ))
        R=$(( $BASESECS - `date '+%s'` ))
        if [[ $R -gt 0 ]]
         then
          sleep $R
        fi
        DT="`date '+%F %T%:z'`"
      fi
      if [[ -n "$section" && -n "$teststep" && -z "$detail" ]]
       then
        h=`echo "${hours:-0}" | sed 's|[,/].*||;s|[*]|0|'`
        m=`echo "${minutes:-0}" | sed 's|[,/].*||;s|[*]|0|'`
        if [[ "$h" = "$STD" && "$m" = "$MIN" ]]
         then
          send_test_doku $S -h "${hostname:-$H}" "$section" "$teststep" "$url"
        fi
      fi
    done
  fi
  rm -f $TMPFILE*
fi
