#!/bin/bash
# bullpen-credential-sync — noether's Claude credential into the rich agents.
#
# WHY THIS IS A CRUTCH AND SAYS SO
# --------------------------------
# @architect and @reviewer need a real Claude login; without it they fall back to
# opencode and become the same model as @foreman and @testdesigner, which turns
# the phase-5 review into a self-review. The clean fix is one `/login` per
# container. This copies noether's credential instead, so three instances share
# one refresh token.
#
# That is a KNOWN risk, accepted deliberately: if the token rotates on refresh,
# whoever refreshes first invalidates the others. This job is the repair, not the
# prevention -- it puts a working credential back after a rotation has broken it.
#
# The interval therefore sets the worst-case outage: weekly means an agent can be
# mute for up to seven days. Change OnCalendar to daily if that turns out to
# bite; nothing else needs to change.
#
# It NEVER puts the token on a command line -- file to stdin to file, so it does
# not appear in the process list on any of the three hosts it passes through.
set -uo pipefail

QUELLE="${HOME}/.claude/.credentials.json"
ZIELE="architect reviewer"
LOG="${HOME}/.local/state/bullpen-credential-sync.log"
PEN="incus exec bullpen --"

mkdir -p "$(dirname "$LOG")"
log() { echo "$(date -Iseconds) $*" | tee -a "$LOG" >&2; }

[ -r "$QUELLE" ] || { log "FAIL: $QUELLE nicht lesbar"; exit 1; }

# Ein leeres Token ist schlimmer als ein altes: es ueberschreibt ein
# funktionierendes durch eine Huelle. Genau so lagen die Container vorher da --
# Datei vorhanden, accessToken "", und claude meldete "OAuth session expired",
# was nach Ablauf klingt und keiner war.
if ! python3 - "$QUELLE" <<'PY'
import json, sys
o = json.load(open(sys.argv[1])).get("claudeAiOauth", {})
sys.exit(0 if o.get("accessToken") and o.get("refreshToken") else 1)
PY
then
    log "FAIL: Quelle traegt kein Token (leere Huelle) — nichts kopiert"
    exit 1
fi

RC=0
for c in $ZIELE; do
    if ! sic hertz $PEN incus exec "$c" -- \
            tee /home/claude/.claude/.credentials.json < "$QUELLE" >/dev/null 2>&1; then
        log "FAIL $c: konnte nicht schreiben"; RC=1; continue
    fi
    sic hertz $PEN incus exec "$c" -- sh -c '
        chown claude:claude /home/claude/.claude/.credentials.json
        chmod 600 /home/claude/.claude/.credentials.json
        systemctl restart bullpen-lurker' >/dev/null 2>&1

    # Nicht "kopiert" melden, sondern "antwortet". Eine Datei am richtigen Ort
    # ist keine funktionierende Anmeldung -- das war der ganze Fehler vorher.
    a=$(sic hertz $PEN incus exec "$c" -- sh -c \
        'su -s /bin/sh claude -c "timeout 120 claude -p --dangerously-skip-permissions OK 2>&1 | tail -1"' 2>&1)
    case "$a" in
        *authenticate*|*expired*|*rror*) log "FAIL $c: kopiert, aber claude antwortet: $a"; RC=1 ;;
        *)                               log "ok $c: claude antwortet" ;;
    esac
done
exit $RC
