#!/bin/sh

# Verify that the ntpd-rs daemon service starts, exposes its observation socket,
# and that ntp-ctl can query its status and Prometheus metrics through it.

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 "Checking that %s is active: " "${NTPD_RS_SERVICE}"
systemctl is-active --quiet "${NTPD_RS_SERVICE}" && __test_ok || __test_fail

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

printf "Querying daemon status with ntp-ctl: "
ntp-ctl status -c "${NTPD_RS_OFFLINE_CONFIG}" && __test_ok || __test_fail

printf "Checking that the plain status reports the synchronization section: "
ntp-ctl status -c "${NTPD_RS_OFFLINE_CONFIG}" | grep -q "Synchronization status" && __test_ok || __test_fail

printf "Querying daemon status in prometheus format: "
ntp-ctl status -f prometheus -c "${NTPD_RS_OFFLINE_CONFIG}" | 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}"
    ntp-ctl status -f prometheus -c "${NTPD_RS_OFFLINE_CONFIG}" \
        | grep -q "^${metric}" && __test_ok || __test_fail
done

exit 0
