#!/bin/sh
ITEM=$1
HOST=localhost
DBPORT=3307
DBPASSWD=`cat /etc/save/mysql_root`
MYSQLBIN='/usr/bin/mysql'
MYSQLADMINBIN='/usr/bin/mysqladmin'
PHP_BIN='/usr/local/php72/bin/php'
DIR=`dirname $0`
CMD="${PHP_BIN} -q $DIR/ss_get_mysql_stats_${DBPORT}.php --host $HOST --items gg"
CACHEFILE="/tmp/percona-monitor-${DBPORT}.txt"

if [ `whoami` == 'root' ];then
    touch ${CACHEFILE} && chown -R zabbix.zabbix ${CACHEFILE}
fi

if [ "$ITEM" = "running-slave" ]; then
    # Check for running slave
    RES=`HOME=~zabbix ${MYSQLBIN} -S ${DBSOCKET} -e 'SHOW SLAVE STATUS\G' | egrep '(Slave_IO_Running|Slave_SQL_Running):' | awk -F: '{print $2}' | tr '\n' ','`
    if [ "$RES" = " Yes, Yes," ]; then
        echo 1
    else
        echo 0
    fi
    exit
elif [ "${ITEM}" = "check-alive" ]; then
    # Check for mysql is alive
    RES=`HOME=~zabbix ${MYSQLADMINBIN}  -S ${DBSOCKET} ping`
    if [ "${RES}" = "mysqld is alive" ]; then
        echo 1
    else
        echo 0
    fi
    exit
elif [ -e $CACHEFILE ]; then
    # Check and run the script
    TIMEFLM=`stat -c %Y ${CACHEFILE}`
    TIMENOW=`date +%s`
    if [ `expr $TIMENOW - $TIMEFLM` -gt 300 ]; then
        rm -f $CACHEFILE
        $CMD 2>&1 > /dev/null
    fi
else
    $CMD 2>&1 > /dev/null
fi

# Parse cache file
if [ -e $CACHEFILE ]; then
    cat $CACHEFILE | sed 's/ /\n/g; s/-1/0/g'| grep $ITEM | awk -F: '{print $2}'
else
    echo "ERROR: run the command manually to investigate the problem: $CMD"
fi
