#!/bin/sh

# Verify that the ntpd-rs-metrics Prometheus exporter serves metrics scraped
# from the running daemon, exposes them as text/plain, and only answers GET.

set -e

. debian/tests/helper-functions

trap __cleanup EXIT

printf "Configuring ntpd-rs with an offline (sourceless) configuration: "
__install_offline_config && __test_ok || __test_fail

printf "Restarting %s: " "${NTPD_RS_SERVICE}"
__restart_ntpd_rs && __test_ok || __test_fail

printf "Waiting for the observation socket %s: " "${NTPD_RS_OBSERVE_SOCKET}"
__wait_for_observe_socket && __test_ok || __test_fail

printf "Starting %s: " "${NTPD_RS_METRICS_SERVICE}"
systemctl --quiet restart "${NTPD_RS_METRICS_SERVICE}" && sleep 3 && __test_ok || __test_fail

printf "Checking that %s is active: " "${NTPD_RS_METRICS_SERVICE}"
systemctl is-active --quiet "${NTPD_RS_METRICS_SERVICE}" && __test_ok || __test_fail

printf "Scraping the Prometheus endpoint at %s/metrics: " "${NTPD_RS_METRICS_ENDPOINT}"
metrics=""
for _ in $(seq 1 15); do
    if metrics=$(curl -fsS "http://${NTPD_RS_METRICS_ENDPOINT}/metrics" 2>/dev/null); then
        break
    fi
    sleep 1
done

echo "${metrics}" | grep -q "^ntp_" && __test_ok || __test_fail

for metric in ntp_uptime_seconds ntp_system_stratum; do
    printf "Checking that the %s metric is exported: " "${metric}"
    echo "${metrics}" | grep -q "^${metric}" && __test_ok || __test_fail
done

printf "Checking that the exporter advertises a text/plain content type: "
curl -fsS -D - -o /dev/null "http://${NTPD_RS_METRICS_ENDPOINT}/metrics" 2>/dev/null \
    | grep -qi "^content-type:[[:space:]]*text/plain" && __test_ok || __test_fail

printf "Checking that a non-GET request is not served: "
if curl -fsS -X POST "http://${NTPD_RS_METRICS_ENDPOINT}/metrics" >/dev/null 2>&1; then
    __test_fail
else
    __test_ok
fi

echo
echo "## Sample of exported metrics:"
echo "${metrics}" | grep "^ntp_" | head -n 10

exit 0
