#!/bin/sh

DEBUG=false
if [ "$1" = "--varlimits-debug" ]; then
   DEBUG=true
   shift
fi

# $1 now contains the actual plugin to exec

case $1 in
   */*)
      SUB_PLUGIN="$1" ;;
   *)
      SUB_PLUGIN="`dirname $0`/$1" ;;
esac

if [ ! -x $SUB_PLUGIN ]; then
   echo "UNKNOWN: Cannot find/execute plugin $SUB_PLUGIN"
   exit 3
fi

shift

# $1 now contains the limits-per-daytime specs.

# Overall syntax:	@frame[@frame...]
# where "frame":	HH[MM[SS]]=[[warn+]crit]
# and the time given is when the stated limits should *start* being applied
# (until the next frame). Times preceding the first frame get the default limits:

LIMITS=""
LASTMATCH="-1"
NOW="`date +%H%M%S | sed -e 's/^0*\(.\)/\1/'`"
PARAM1="$1"

$DEBUG && ( echo "Current time: $NOW" ; echo "Parsing spec: $PARAM1" )
while [ "$PARAM1" != "" ]; do
   $DEBUG && echo "   Remaining spec: $PARAM1"
   FRAME=`echo "$PARAM1" | sed -e 's/^@//' -e 's/^\([^@]*\)@.*/\1/'`
   $DEBUG && echo "      Inspecting frame: $FRAME"
   START=`echo "$FRAME" | sed -e 's/=.*/000000/' -e 's/^\(......\).*/\1/' -e 's/^0*\(.\)/\1/'`
   WARN=`echo "$FRAME" | sed -e 's/.*=//' -e 's/[^+]*$//' -e 's/+$//'`
   CRIT=`echo "$FRAME" | sed -e 's/.*=//' -e 's/^[^+]*+//'`
   $DEBUG && echo "         Frame starts at $START, warn='$WARN', crit='$CRIT'"
   if [ $NOW -lt $START ]; then
      $DEBUG && echo "         Frame hasn't started yet."
   elif [ $START -le $LASTMATCH ]; then
      $DEBUG && echo "         Frame has already been supplanted by a later one."
   else
      LASTMATCH=$START
      if [ "$WARN" != "" -a "$CRIT" != "" ]; then
         LIMITS="--warning $WARN --critical $CRIT"
      elif [ "$WARN" != "" ]; then
         LIMITS="--warning $CRIT"
      elif [ "$CRIT" != "" ]; then
         LIMITS="--critical $CRIT"
      else
         LIMITS=""
      fi
      $DEBUG && echo "         Frame applies, limits set to '$LIMITS'"
   fi
   PARAM1=`echo "$PARAM1" | sed -e 's/^.[^@]*//'`
done
$DEBUG && echo "Applied limits: '$LIMITS'"

shift

exec $SUB_PLUGIN $LIMITS "$@"

echo "UNKNOWN: Cannot exec $SUB_PLUGIN $LIMITS $@"
exit 3
