#!/bin/bash
# bee-autoaudit — once bee-web is actually serving, queue one Audit task
# through the same task queue the "Run Audit" button in the UI uses. Without
# this, an operator who opens the web UI right after boot sees an empty task
# history and has to trigger Audit by hand; this makes that the default so
# there's already a completed run (with its report/charts) waiting for them.
#
# Runs once per boot (see bee-autoaudit.service, After=bee-web.service +
# the boot-time bee-audit/preflight/network units). Deliberately best-effort:
# any failure here just means the operator falls back to the manual button,
# so every exit path is 0 and failures only go to the log.

set -u

LOG_PREFIX="bee-autoaudit"
WEB_TIMEOUT_SECS=120

log() {
    echo "[${LOG_PREFIX}] $*"
}

web_healthy() {
    bash -c 'exec 3<>/dev/tcp/127.0.0.1/80 && printf "GET /healthz HTTP/1.0\r\nHost: localhost\r\n\r\n" >&3 && grep -q "^ok$" <&3' \
        >/dev/null 2>&1
}

elapsed=0
until web_healthy; do
    if [ "$elapsed" -ge "$WEB_TIMEOUT_SECS" ]; then
        log "WARN: bee-web did not become healthy within ${WEB_TIMEOUT_SECS}s, giving up"
        exit 0
    fi
    sleep 2
    elapsed=$((elapsed + 2))
done

response=$(curl -sf -X POST http://127.0.0.1/api/audit/run 2>&1)
rc=$?
if [ "$rc" -ne 0 ]; then
    log "WARN: failed to queue Audit task (curl exit $rc): $response"
    exit 0
fi
log "queued Audit task: $response"
