#!{{ bash }}

set -e

APACHEDEX_FILE='{{ apdex_file }}/ApacheDex-'$(date +%Y-%m-%d)'.html'
APACHEDEX_REPORT_JSON_FILE={{ apdex_status_file }} 
DESIRED_THRESHOLD={{ user_threshold }}

# Check if the file is there
if [ ! -s "$APACHEDEX_FILE" ]; then 
  # If file doesn't exists create one
  # If it is empty check for modification time
  if [ ! -f "$APACHEDEX_FILE" ]; then
    touch $APACHEDEX_FILE
  else
    MODIFIED_DATE=`stat -c '%Z' $APACHEDEX_FILE`
    CURRENT_DATE=`date +%s`
    if [[ `echo "$CURRENT_DATE - $MODIFIED_DATE" | bc` -gt 108000 ]]
    then 
      echo "File modification date is greater than 30 hours"
      JSON_CONTENT=`cat $APACHEDEX_REPORT_STATUS_FILE`
      MESSAGE=`echo $JSON_CONTENT | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["message"]'`
      echo $MESSAGE
      exit 2
    else
      echo "File is empty for now"
    fi
  fi
else
  # Check if the result exists
  {
    REGEX="<th>apdex.*?<tr><td [^<]*>(.*?)%<\/td>"
    FILE_CONTENT=`cat $APACHDEX_FILE`
    if [[ $FILE_CONTENT =~ $REGEX ]]
    then
      RESULT=${BASH_REMATCH[1]}
      RESULT=${THRESHOLD:-0}
      if [[ `echo "$RESULT > $DESIRED_THRESHOLD" | bc` -eq 1 ]]
      then
        echo "Your score is $RESULT %, Thanks for keeping it all clean"
      else
        echo "Threshold is lower than exptected: Expected was $DESIRED_THRESHOLD % and we current is $RESULT %"
        exit 2
      fi
    else
      echo "No threshold found in the result"
    fi
  } || {
    echo "Cannot parse the apdex result"
  }
fi