#!/bin/sh 
#
# Script to make a proxy (ie HAProxy) capable of monitoring Percona XtraDB Cluster nodes properly
#
# Authors:
# Raghavendra Prabhu <raghavendra.prabhu@percona.com>
# Olaf van Zandwijk <olaf.vanzandwijk@nedap.com>
# Olivier Bouffet <production@infomaniak.com>
# Thomas Goirand <zigo@debian.org>
#
# Based on the original script from Unai Rodriguez and Olaf (https://github.com/olafz/percona-clustercheck)
#
# This was then simplified by Zigo to "just work" within a Debian package without any customization.

set -e

TIMEOUT=10
MYSQL_CMDLINE="mysql --defaults-extra-file=/etc/mysql/my.cnf -n --connect-timeout=$TIMEOUT"

wsrep_local_state=$(${MYSQL_CMDLINE} -B -e "SHOW GLOBAL STATUS WHERE Variable_name='wsrep_local_state';" | tail -n 1 | awk '{print $2}')
wsrep_cluster_status=$(${MYSQL_CMDLINE} -B -e "SHOW GLOBAL STATUS WHERE Variable_name='wsrep_cluster_status';" | tail -n 1 | awk '{print $2}')

if [ "${wsrep_cluster_status}" = 'Primary' ] && [ ${wsrep_local_state} -eq 4 ] ; then 
	READ_ONLY=$($MYSQL_CMDLINE -B -e "SHOW GLOBAL VARIABLES WHERE Variable_name='read_only';" | tail -n 1 | awk '{print $2}')
        if [ "${READ_ONLY}" = "ON" ] ; then
		# Percona XtraDB Cluster node local state is 'Synced', but it is in
		# read-only mode. The variable AVAILABLE_WHEN_READONLY is set to 0.
		# => return HTTP 503
		# Shell return-code is 1
		echo "HTTP/1.1 503 Service Unavailable"
		echo "Content-Type: text/plain"
		echo "Connection: close"
		echo "Content-Length: 43"
		echo ""
		echo "Percona XtraDB Cluster Node is read-only."
		sleep 1
		exit 1
	fi

	# Percona XtraDB Cluster node local state is 'Synced' => return HTTP 200
	# Shell return-code is 0
	echo "HTTP/1.1 200 OK"
	echo "Content-Type: text/plain"
	echo "Connection: close"
	echo "Content-Length: 40"
	echo ""
	echo "Percona XtraDB Cluster Node is synced."
	sleep 1
	exit 0
else
	# Percona XtraDB Cluster node local state is not 'Synced' => return HTTP 503
	# Shell return-code is 1
	echo "HTTP/1.1 503 Service Unavailable"
	echo "Content-Type: text/plain"
	echo "Connection: close"
	echo "Content-Length: 56"
	echo ""
	echo "Percona XtraDB Cluster Node is not synced or non-PRIM."
	sleep 1
	exit 1
fi
