#!/bin/bash
# Aria Service Curator (KAR-475)
# Triggered weekly via systemd timer.
# Scans systemd aria-* services + cron-jobs + hooks against Barry-Zhang
# "Embarrassingly Simple" test: does it deliver value, or can a workflow replace it?
#
# Defense-in-Depth: This script READS only. It does not stop, disable, or
# delete anything. It generates a Markdown report with recommendations.

set -e

REPORT_DIR="$HOME/aria/brain/02-Wissen/service-curator-reports"
DATE=$(date +%Y-%m-%d)
REPORT="${REPORT_DIR}/service-curator-${DATE}.md"
mkdir -p "$REPORT_DIR"

# Thresholds
INACTIVE_DAYS_WARN=14    # service inactive > 14d -> mark as low-value
LARGE_SCRIPT_LOC=400     # script > 400 LOC -> mark as candidate for split
FAILED_RECENT_HOURS=72   # failed in last 72h -> mark as broken

cat > "$REPORT" << EOF
---
title: Service Curator Report ${DATE}
type: audit
tags: [service-curator, audit, autonomous, kar-475]
date: ${DATE}
status: aktiv
related: [[CLAUDE]], [[HEARTBEAT]], [[02-Wissen/barry-zhang-anthropic-dont-build-agents-2026-05-21]]
---

# Service Curator Report ${DATE}

> Wochen-Scan aller \`aria-*\` systemd-Services + Cron + Hooks.
> Erzeugt von \`/root/aria/scripts/aria-service-curator.sh\`.
> Defense-in-Depth: Skript loescht/disabled NICHTS — nur Vorschlaege.

## Methodik

Barry-Zhang-Test ("Don't build an agent. Build a workflow.")
([brain](02-Wissen/barry-zhang-anthropic-dont-build-agents-2026-05-21.md)):

1. **Was liefert dieser Service?** Konkretes Output, nicht "Health-Check" abstrakt.
2. **Kann ein einfacher Cron + Skript das Gleiche?** Wenn ja → vereinfachen.
3. **Wann lief er zuletzt erfolgreich?** > ${INACTIVE_DAYS_WARN}d ohne erfolgreichen Run → Pruefkandidat.
4. **Wie gross ist das Backing-Skript?** > ${LARGE_SCRIPT_LOC} LOC → Split-Kandidat.

## Service-Inventar

EOF

# ── Section 1: All aria-* services ────────────────────────
echo "" >> "$REPORT"
echo "### 1. Alle \`aria-*\` Services" >> "$REPORT"
echo "" >> "$REPORT"

SERVICE_LIST=$(systemctl list-units --type=service --all --no-legend 2>/dev/null \
    | awk '$1 ~ /^aria/ {print $1}' \
    | sort -u)

TOTAL=$(echo "$SERVICE_LIST" | grep -c . || true)
ACTIVE=$(systemctl list-units --type=service --all --no-legend 2>/dev/null \
    | awk '$1 ~ /^aria/ && $3 == "active" {print $1}' \
    | wc -l)
INACTIVE=$((TOTAL - ACTIVE))

echo "Total: **${TOTAL}** Services (${ACTIVE} aktiv, ${INACTIVE} inaktiv)" >> "$REPORT"
echo "" >> "$REPORT"
echo "| Service | Status | Last-Run-Result | Recommendation |" >> "$REPORT"
echo "|---|---|---|---|" >> "$REPORT"

while IFS= read -r svc; do
    [ -z "$svc" ] && continue
    STATUS=$(systemctl show -p ActiveState --value "$svc" 2>/dev/null || echo "unknown")
    LAST_RESULT=$(systemctl show -p Result --value "$svc" 2>/dev/null || echo "unknown")
    EXEC_MAIN_START=$(systemctl show -p ExecMainStartTimestamp --value "$svc" 2>/dev/null)

    # Recommendation logic
    REC="—"
    if [ "$STATUS" = "active" ]; then
        REC="OK (running)"
    elif [ "$LAST_RESULT" = "exit-code" ] || [ "$LAST_RESULT" = "core-dump" ] || [ "$LAST_RESULT" = "signal" ]; then
        REC="**FIX or REMOVE** — failed result=${LAST_RESULT}"
    elif [ -z "$EXEC_MAIN_START" ]; then
        REC="VERIFY — never ran"
    fi

    echo "| \`${svc}\` | ${STATUS} | ${LAST_RESULT} | ${REC} |" >> "$REPORT"
done <<< "$SERVICE_LIST"

# ── Section 2: All aria-* timers ───────────────────────────
echo "" >> "$REPORT"
echo "### 2. Alle \`aria-*\` Timer (Cron-Aequivalent)" >> "$REPORT"
echo "" >> "$REPORT"

TIMER_LIST=$(systemctl list-timers --all --no-legend 2>/dev/null \
    | awk '$NF ~ /^aria/ {print $NF}' \
    | sort -u)

TIMER_TOTAL=$(echo "$TIMER_LIST" | grep -c . || true)
echo "Total: **${TIMER_TOTAL}** Timer" >> "$REPORT"
echo "" >> "$REPORT"
echo "| Timer | Last-Triggered | Next-Run | Schedule |" >> "$REPORT"
echo "|---|---|---|---|" >> "$REPORT"

while IFS= read -r tmr; do
    [ -z "$tmr" ] && continue
    LAST_TRIG=$(systemctl show -p LastTriggerUSec --value "$tmr" 2>/dev/null || echo "—")
    NEXT_TRIG=$(systemctl show -p NextElapseUSecRealtime --value "$tmr" 2>/dev/null || echo "—")
    SCHEDULE=$(systemctl cat "$tmr" 2>/dev/null | grep -E "^On(Calendar|Unit)" | head -1 | sed 's/^[[:space:]]*//')
    echo "| \`${tmr}\` | ${LAST_TRIG:-—} | ${NEXT_TRIG:-—} | ${SCHEDULE:-—} |" >> "$REPORT"
done <<< "$TIMER_LIST"

# ── Section 3: Failed-recently services ────────────────────
echo "" >> "$REPORT"
echo "### 3. Kuerzlich gescheiterte Services" >> "$REPORT"
echo "" >> "$REPORT"

FAILED=$(systemctl --failed --no-legend 2>/dev/null | awk '$1 ~ /^aria/ {print $1}')
FAIL_COUNT=$(echo "$FAILED" | grep -c . || true)

if [ "$FAIL_COUNT" -eq 0 ]; then
    echo "Keine aktuell gescheiterten aria-Services. ✓" >> "$REPORT"
else
    echo "**${FAIL_COUNT} Services im Failed-State:**" >> "$REPORT"
    echo "" >> "$REPORT"
    while IFS= read -r f; do
        [ -z "$f" ] && continue
        echo "- \`${f}\`" >> "$REPORT"
    done <<< "$FAILED"
fi

# ── Section 4: Large backing scripts ──────────────────────
echo "" >> "$REPORT"
echo "### 4. Grosse Backing-Skripte (> ${LARGE_SCRIPT_LOC} LOC)" >> "$REPORT"
echo "" >> "$REPORT"
echo "Kandidaten fuer Split oder Workflow-Vereinfachung:" >> "$REPORT"
echo "" >> "$REPORT"
echo "| Datei | LOC |" >> "$REPORT"
echo "|---|---|" >> "$REPORT"

find /root/aria/scripts -maxdepth 1 -type f \( -name "*.sh" -o -name "*.py" \) 2>/dev/null \
    | while read -r f; do
        LOC=$(wc -l < "$f" 2>/dev/null || echo 0)
        if [ "$LOC" -gt "$LARGE_SCRIPT_LOC" ]; then
            BASENAME=$(basename "$f")
            echo "| \`${BASENAME}\` | ${LOC} |" >> "$REPORT"
        fi
    done

# ── Section 5: Inactive services (Pruefkandidaten) ─────────
echo "" >> "$REPORT"
echo "### 5. Inaktive Services ohne Last-Run" >> "$REPORT"
echo "" >> "$REPORT"
echo "Services die never-run sind oder lange nicht aktiv waren — Barry-Zhang-Test:" >> "$REPORT"
echo "Liefern die etwas Konkretes? Wenn nein, in v6 Sprint entfernen." >> "$REPORT"
echo "" >> "$REPORT"
echo "| Service | Last-Active |" >> "$REPORT"
echo "|---|---|" >> "$REPORT"

while IFS= read -r svc; do
    [ -z "$svc" ] && continue
    STATUS=$(systemctl show -p ActiveState --value "$svc" 2>/dev/null || echo "unknown")
    if [ "$STATUS" != "active" ]; then
        EXEC_LAST=$(systemctl show -p ExecMainExitTimestamp --value "$svc" 2>/dev/null)
        if [ -z "$EXEC_LAST" ] || [ "$EXEC_LAST" = "n/a" ]; then
            echo "| \`${svc}\` | NEVER |" >> "$REPORT"
        else
            echo "| \`${svc}\` | ${EXEC_LAST} |" >> "$REPORT"
        fi
    fi
done <<< "$SERVICE_LIST"

# ── Section 6: Recommendation Summary ──────────────────────
echo "" >> "$REPORT"
echo "### 6. Empfehlungs-Summary" >> "$REPORT"
echo "" >> "$REPORT"
cat >> "$REPORT" << SUMEOF
**Pro Service-Eintrag in Section 1 mit "FIX or REMOVE":**

1. \`journalctl -u <service> --since '7 days ago' --no-pager\` checken.
2. Wenn nichts Sinnvolles liefert: zu \`disable\` plus Backup-Note in
   \`02-Wissen/service-curator-removals/\` mit Begruendung.
3. Wenn Sinn liefert aber kaputt: Bug-Issue in Linear KAR mit
   Service-Name plus Stack-Trace im Body.

**Pro grosses Skript in Section 4:**

1. Kann es in 2-3 kleinere Skripte gesplittet werden (Single-Responsibility)?
2. Ist die Komplexitaet noetig oder Workflow-ersetzbar (Barry-Zhang)?

**Pro never-run Service in Section 5:**

1. Existiert das Backing-Skript noch? \`systemctl cat <service>\` checken.
2. Wenn das Skript fehlt: \`systemctl disable\` plus File-Remove.
3. Wenn das Skript existiert: warum lief es nie? Cron-Problem oder kein-Aufruf?

Report-File: \`${REPORT}\`
SUMEOF

echo "Service-Curator Report geschrieben: ${REPORT}"

# Optional: Telegram-Ping wenn FAIL_COUNT > 0
if [ "$FAIL_COUNT" -gt 0 ] && [ -n "$TG_TOKEN" ] && [ -n "$TG_CHAT_ID" ]; then
    curl -s -X POST "https://api.telegram.org/bot${TG_TOKEN}/sendMessage" \
        -d "chat_id=${TG_CHAT_ID}" \
        -d "text=Service-Curator: ${FAIL_COUNT} aria-* Services im Failed-State. Report: ${REPORT}" > /dev/null
fi
