#!/bin/bash
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License along
#   with this program; if not, write to the Free Software Foundation, Inc.,
#   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


WHAT="$1"
PORT="${2:-80}"
HOSTNAME="${3:-127.0.0.1}"
if [ -z "$WHAT" ];then
   echo "$0 reader|writer|keepalive|total|all|accesses|kbytes"
   exit 1
fi


if [ "$WHAT" == "accesses" ] || [ "$WHAT" == "kbytes" ];then
  wget -q --timeout=5 --user-agent "ZABBIX" -O- "http://$HOSTNAME:$PORT/server-status?auto"|awk -v get=$WHAT '
     /Total Accesses:/{
         if (get == "accesses"){
            printf("%s",$3);
	 }
     }
     /Total kBytes:/{
         if (get == "kbytes"){
            printf("%s",$3);
	 }
     }
'
else
wget -q --timeout=5 --user-agent "ZABBIX" -O- "http://$HOSTNAME:$PORT/server-status?auto"|\
awk -v get=$WHAT '
  BEGIN{
	readers = 0; writers = 0; keepalives = 0; total = 0;
  }
  /Scoreboard:/{
    scoreboard = $0;
    print scoreboard > "/dev/stderr" ;
    sub(/^Scoreboard: /, "", scoreboard);
    total = length(scoreboard);
    for(i=0;i<=length(scoreboard);i++){
	     what = substr(scoreboard, i , 1)
        if(what == "W"){
	       writers++;	
        }
        else if (what == "R"){
	      readers++;
        }
        else if (what == "K"){
	      keepalives++;
        }
    }	
  }
  END{
	if (total == 0){
           print "FAIL: Unable to get scoreboard" > "/dev/stderr";
           print "FAIL" ;
           exit;
        }
	if(get == "reader"){
	         print readers;
        }
	else if(get == "writer"){
	         print writers;
        }
	else if(get == "keepalive"){
	         print keepalives;
        }
   else if(get == "total"){
	         print total;
        }
   else if(get == "all"){
	         print "Reader " readers ", Writer " writers ", Keepalive " keepalives ", Total " total;
        }
   else{
	         print "Reader " readers ", Writer " writers ", Keepalive " keepalive ", Total " total > "/dev/stderr";
        }
  }
'
fi
