#!/usr/bin/env bash
set -uo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
DEPLOY_SCRIPT="$ROOT/packaging/deploy-local.sh"
UNIT="$ROOT/packaging/overdeck-collector-startup-boost.service"
fails=0
check() {
  if (( $1 == 0 )); then printf 'ok - %s\n' "$2"
  else printf 'FAIL - %s\n' "$2"; fails=$((fails + 1)); fi
}

if systemd-analyze verify "$UNIT" >"${XDG_CACHE_HOME:-$HOME/.cache}/collector-startup-boost-verify.$$" 2>&1; then rc=0; else rc=1; fi
check "$rc" 'the bounded startup boost is a valid systemd unit'
rm -f "${XDG_CACHE_HOME:-$HOME/.cache}/collector-startup-boost-verify.$$"

if grep -qxF 'RuntimeMaxSec=120' "$UNIT" \
  && grep -qxF 'ExecStart=/usr/bin/systemctl --user set-property --runtime overdeck-collector.service CPUQuota=100%%' "$UNIT" \
  && grep -qxF 'ExecStop=/usr/bin/systemctl --user set-property --runtime overdeck-collector.service CPUQuota=25%%' "$UNIT"; then rc=0; else rc=1; fi
check "$rc" 'startup uses full CPU and automatically restores the 25 percent steady quota'

python3 - "$DEPLOY_SCRIPT" <<'PY'
import sys
text = open(sys.argv[1], encoding="utf-8").read()
start = text.index("if (( collector_work_needed )); then", text.index("bash \"${DEPLOY}/packaging/install.sh\""))
end = text.index("publish_component_receipt collector", start)
block = text[start:end]
needles = (
    "systemctl --user start overdeck-collector-startup-boost.service",
    "collector_activation_started_ms=$(date +%s%3N)",
    'backend-release.sh" activate collector',
    "collector_activation_finished_ms=$(date +%s%3N)",
    "systemctl --user stop overdeck-collector-startup-boost.service",
    "collector-startup-boost-restore-failed",
    'case "$collector_activation_rc" in',
)
positions = [block.index(needle) for needle in needles]
assert positions == sorted(positions), positions
assert "collector exact readiness in %dms; steady CPU quota restored" in block
PY
check $? 'deployment restores the quota before classifying candidate or rollback results'

(( fails == 0 )) || { printf '%s check(s) failed\n' "$fails" >&2; exit 1; }
printf 'collector-startup-boost: all checks passed\n'
