#!/bin/bash
# Ansible managed

set -euo pipefail

TMPDIR=/dev/shm
SOCKET=/run/haproxy/monitoring.sock
TMPFILE=$TMPDIR/haproxy_info.tmp
CACHEFILE=$TMPDIR/haproxy_info.txt
CACHE_EXPIRATION_TIME_SECONDS=60
METRIC=$1

refresh_cache_file () {
	echo "show info" | socat /run/haproxy/monitoring.sock stdio > $TMPFILE
	# rsync is atomic
	rsync -t $TMPFILE $CACHEFILE
}

# if either the tmpfile or the cachefile is not here, do the refresh
if ! [ -f $TMPFILE ] || ! [ -f $CACHEFILE ]; then
	refresh_cache_file
fi

# if the cache file is too old, do the refresh
CACHEFILE_TIMESTAMP=$(stat -c %Y $CACHEFILE)
if [ ${CACHEFILE_TIMESTAMP} -lt $(date -d "60 second ago" "+%s") ]; then
	refresh_cache_file
fi

# we need a special case for "Unstoppable Jobs" because that's the only metric with a space in its name
if [ $METRIC == "UnstoppableJobs" ]; then
	egrep "^Unstoppable Jobs: " $CACHEFILE | sed "s/^Unstoppable Jobs: //"
else
	egrep "^$METRIC: " $CACHEFILE | sed "s/^$METRIC: //"
fi
