#!/bin/sh -e
#
# This is a functional test which passes if prometheus-varnish-exporter returns
# the metric 'varnish_up' with the value 1. This means that:
# - prometheus-varnish-exporter.service has been started correctly
# - the exporter can run varnishstat(1) successfully
# - metrics are being returned as expected

status_and_exit() {
  systemctl status varnish.service
  systemctl status prometheus-varnish-exporter.service
  exit 1
}

if [ "$(id --user)" = 0 ] || id --groups --name | grep -qw varnish; then

if ! varnishstat -1 -f MGT.uptime; then
  echo "varnishstat does not work!" >&2
  status_and_exit
fi

if ! prometheus-varnish-exporter --test; then
  echo "prometheus-varnish-exporter --test failed!" >&2
  status_and_exit
fi

fi

if ! systemctl -q is-active prometheus-varnish-exporter.service; then
  echo "prometheus-varnish-exporter.service is not active!" >&2
  status_and_exit
fi

if ! curl 127.0.0.1:9131/metrics > metrics; then
  echo "Scraping the exporter failed!" >&2
  status_and_exit
fi

if ! grep -q '^varnish_up 1$' metrics; then
  echo "The varnish_up metric is missing or != 1!" >&2
  echo
  cat metrics
  status_and_exit
fi

