#!/bin/bash
# Ansible managed
# modified from https://raw.githubusercontent.com/anapsix/zabbix-haproxy/master/haproxy_discovery.sh
# Get list of Frontends and Backends from HAPROXY
# Example: ./haproxy_discovery.sh FRONTEND|BACKEND|SERVERS
# the argument should be either FRONTEND, BACKEND or SERVERS, will default to FRONTEND if not set

HAPROXY_SOCK="/run/haproxy/monitoring.sock"

query_stats() {
	echo "show stat" | socat ${HAPROXY_SOCK} stdio 2>/dev/null
}

get_stats() {
	echo "$(query_stats)" | grep -v "^#"
}

case $1 in
	B*) END="BACKEND" ;;
	F*) END="FRONTEND" ;;
	S*)
		for backend in $(get_stats | grep BACKEND | cut -d, -f1 | uniq); do
			for server in $(get_stats | grep "^${backend}," | grep -v BACKEND | cut -d, -f2); do
				serverlist="$serverlist, "'{ "{#BACKEND_NAME}": "'$backend'","{#SERVER_NAME}": "'$server'" }'
			done
		done
		echo -e '{ "data": [ '${serverlist#,}'] }'
		exit 0
	;;
	*) END="FRONTEND" ;;
esac

for frontend in $(get_stats | grep "$END" | cut -d, -f1 | uniq); do
    felist="$felist,"'{ "{#'${END}'_NAME}": "'$frontend'" }'
done
echo -e '{ "data": [ '${felist#,}']}'
