#!/bin/sh
# Copyright (C) 2025 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

OMD_SITE=$(whoami)
SITE_VERSION="$(realpath ~/version | sed 's|.*/||')"
LD_LIBRARY_PATH="/omd/versions/${SITE_VERSION}/lib:${LD_LIBRARY_PATH}"
export LD_LIBRARY_PATH

waitmax_for_unixcat() {
    # DO NOT ACCESS /omd/sites/${site}/bin/cmd directly.
    # bin might point anywhere -> priv escalation.
    waitmax "${1}" "/omd/versions/${SITE_VERSION}/bin/unixcat" ~/tmp/run/"${2}"
}

echo '<<<livestatus_status:sep(59)>>>'
if [ -S ~/tmp/run/live ]; then
    echo "[${OMD_SITE}]"
    echo "GET status" |
        waitmax_for_unixcat 3 "live"
fi

echo '<<<livestatus_ssl_certs:sep(124)>>>'
echo "[${OMD_SITE}]"
for PEM_PATH in ~/etc/ssl/ca.pem ~/etc/ssl/sites/${OMD_SITE}.pem; do
    if [ -f "${PEM_PATH}" ]; then
        CERT_DATE=$(openssl x509 -enddate -noout -in "${PEM_PATH}" | sed 's/notAfter=//')
        echo "${PEM_PATH}|$(date --date="${CERT_DATE}" --utc +%s)"
    fi
done

echo '<<<mkeventd_status:sep(0)>>>'
if [ -S ~/tmp/run/mkeventd/status ]; then
    echo "[\"${OMD_SITE}\"]"
    (echo "GET status" && echo "OutputFormat: json") |
        waitmax_for_unixcat 3 "mkeventd/status"
fi

echo '<<<cmk_site_statistics:sep(59)>>>'
if [ -S ~/tmp/run/live ]; then
    echo "[${OMD_SITE}]"
    waitmax_for_unixcat 5 "live" <<LimitString
GET hosts
Stats: state = 0
Stats: scheduled_downtime_depth = 0
StatsAnd: 2
Stats: state = 1
Stats: scheduled_downtime_depth = 0
StatsAnd: 2
Stats: state = 2
Stats: scheduled_downtime_depth = 0
StatsAnd: 2
Stats: scheduled_downtime_depth > 0
Filter: custom_variable_names < _REALNAME
LimitString
    waitmax_for_unixcat 5 "live" <<LimitString
GET services
Stats: state = 0
Stats: scheduled_downtime_depth = 0
Stats: host_scheduled_downtime_depth = 0
Stats: host_state = 0
Stats: host_has_been_checked = 1
StatsAnd: 5
Stats: scheduled_downtime_depth > 0
Stats: host_scheduled_downtime_depth > 0
StatsOr: 2
Stats: scheduled_downtime_depth = 0
Stats: host_scheduled_downtime_depth = 0
Stats: host_state != 0
StatsAnd: 3
Stats: state = 1
Stats: scheduled_downtime_depth = 0
Stats: host_scheduled_downtime_depth = 0
Stats: host_state = 0
Stats: host_has_been_checked = 1
StatsAnd: 5
Stats: state = 3
Stats: scheduled_downtime_depth = 0
Stats: host_scheduled_downtime_depth = 0
Stats: host_state = 0
Stats: host_has_been_checked = 1
StatsAnd: 5
Stats: state = 2
Stats: scheduled_downtime_depth = 0
Stats: host_scheduled_downtime_depth = 0
Stats: host_state = 0
Stats: host_has_been_checked = 1
StatsAnd: 5
Filter: host_custom_variable_names < _REALNAME
LimitString
fi
