#!/usr/bin/env bash
#
# What is this host deploying, and is the receiver actually healthy?
#
# Written because "the timer is active" was never proof of anything in this
# fleet -- the same lesson the uas-ng updater documents. This shows the daemon,
# the socket, and how the last deploy for each target ended.

set -Eeuo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
readonly REPO_ROOT="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
readonly STATE_DIR="${XDG_STATE_HOME:-${HOME}/.local/state}/cd-webhook"
readonly CONFIG_DIR="${XDG_CONFIG_HOME:-${HOME}/.config}/cd-webhook"
readonly UNIT_NAME="cd-webhook.service"

bold() { printf '\n\033[1m%s\033[0m\n' "$*"; }

bold "Host"
# Capture first: `eval ""` succeeds, so evaluating the failed call inline made
# the branch below unreachable and tripped `set -u` instead.
if host_config="$("${REPO_ROOT}/bin/cd-target" host-config 2>/dev/null)"; then
    eval "$host_config"
    printf '  %s, receiver on %s:%s\n' "$CD_HOST" "$CD_BIND" "$CD_PORT"
else
    printf '  %s is not configured in targets.json\n' "$(hostname)"
    printf '  answers to: %s\n' "$("${REPO_ROOT}/bin/cd-target" hostnames)"
fi

bold "Receiver"
state="$(systemctl --user is-active "$UNIT_NAME" 2>/dev/null || true)"
printf '  %-12s %s\n' "state" "${state:-not installed}"
if [[ "$state" == "active" ]]; then
    printf '  %-12s %s\n' "since" \
        "$(systemctl --user show "$UNIT_NAME" -p ActiveEnterTimestamp --value)"
    if command -v ss >/dev/null 2>&1 && [[ -n "${CD_PORT:-}" ]]; then
        if ss -ltn 2>/dev/null | grep -q ":${CD_PORT}\b"; then
            printf '  %-12s listening on port %s\n' "socket" "$CD_PORT"
        else
            printf '  %-12s \033[31mNOT listening on port %s\033[0m\n' "socket" "$CD_PORT"
        fi
    fi
fi

if [[ -f "${CONFIG_DIR}/hooks.json" ]]; then
    bold "Hook endpoints"
    "${REPO_ROOT}/bin/cd-render-hooks" --list-urls \
        --output "${CONFIG_DIR}/hooks.json" | sed 's/^/  /'
fi

bold "Targets on this host"
mapfile -t targets < <("${REPO_ROOT}/bin/cd-target" list 2>/dev/null || true)
if [[ ${#targets[@]} -eq 0 ]]; then
    printf '  none\n'
else
    for target in "${targets[@]}"; do
        # cd-deploy writes this on every terminal outcome. Reading a record
        # beats grepping the log for phrases the log is free to reword.
        status_file="${STATE_DIR}/${target}.status"
        if [[ -f "$status_file" ]]; then
            IFS=$'\t' read -r when result sha message < "$status_file" || true
            printf '  %-22s %s  %-4s %s  %s\n' \
                "$target" "$when" "$result" "$sha" "$message"
        else
            printf '  %-22s %s\n' "$target" "never deployed from this host"
        fi
    done
fi

bold "Recent receiver log"
journalctl --user -u "$UNIT_NAME" -n 15 --no-pager 2>/dev/null \
    || printf '  (no journal entries)\n'
echo
