CHAT_OUTPUT_BEGIN
COMMAND_ID=RUNTIME-RECEIVER-BLOCK-024
STATUS=OK
RC=0
HOST=pve01
MODE=read-only
COMPONENT=gitea-runtime
REFERENCE_REGISTER_CHECK=OK
REFERENCE_SHA256=f6f7749fda946015116cdbbd754c7e7f20356b4a6cf4df330a1b0b8fdf59cbb2
ERROR_REGISTER_CHECK=OK
ERROR_REGISTER_SHA256=ab8308549db90d235b591af0581580c3c7ba1b287b129cc6111c2eef0a0f9ecc
COMMAND_SHA256=03de81eb7223c7f9d0a547ee58a3bc445df4b6aaa0e96535274791c8e6a2f588
DUPLICATE_FAILED_COMMAND_BLOCKED=false
EXECUTION_STARTED=true
CHANGES_MADE=false
SANITIZED=yes
SECRETS_INCLUDED=no
PRIVATE_ADDRESSES_INCLUDED=no
RAW_EVIDENCE_SHA256=bd6112182f1e657fe1f32a60b9224edd91f45d6c4fc41b0637caaaf3686aefde
SANITIZED_OUTPUT_SHA256=bd6112182f1e657fe1f32a60b9224edd91f45d6c4fc41b0637caaaf3686aefde
OUTPUT_BEGIN
COMMIT_SHA="$(
    docker exec \
        -u "${GIT_UID}:${GIT_GID}" \
        -e COMMAND_ID="$COMMAND_ID" \
        -e PUBLISHED_AT="$PUBLISHED_AT" \
        -e WORK_CONTAINER="$WORK_CONTAINER" \
        gitea sh -lc '
set -eu

BARE="/data/git/repositories/homelab-admin/homelab-public-context.git"
STAGE="/data/gitea/runtime-stage"
WORK="$WORK_CONTAINER"

rm -rf "$WORK"

git clone --quiet "$BARE" "$WORK"

cd "$WORK"

git config user.name "homelab-runtime-publisher"
git config user.email "homelab-runtime@localhost"

if git show-ref \
    --verify \
    --quiet \
    refs/remotes/origin/assistant-runtime
then
    git checkout \
        --quiet \
        -B assistant-runtime \
        origin/assistant-runtime
else
    git checkout \
        --quiet \
        --orphan assistant-runtime

    git rm -rf . >/dev/null 2>&1 || true
fi

mkdir -p runtime/history

cp "$STAGE/latest.json" runtime/latest.json
cp "$STAGE/latest.txt" runtime/latest.txt
cp "$STAGE/latest.json" "runtime/history/${COMMAND_ID}.json"
cp "$STAGE/latest.txt" "runtime/history/${COMMAND_ID}.txt"
cp "$STAGE/README.md" README.md

git add \
    README.md \
    runtime/latest.json \
    runtime/latest.txt \
    "runtime/history/${COMMAND_ID}.json"

git add "runtime/history/${COMMAND_ID}.txt"

if ! git diff --cached --quiet
then
    GIT_AUTHOR_DATE="$PUBLISHED_AT" \
    GIT_COMMITTER_DATE="$PUBLISHED_AT" \
        git commit \
            --quiet \
            -m "runtime: publish ${COMMAND_ID}"
fi

COMMIT="$(git rev-parse HEAD)"

git --git-dir="$BARE" \
    fetch \
    --quiet \
    "$WORK" \
    refs/heads/assistant-runtime

OLD="$(
    git --git-dir="$BARE" \
        rev-parse refs/heads/assistant-runtime \
        2>/dev/null ||
    true
)"

if [ -n "$OLD" ]
then
    git --git-dir="$BARE" \
        update-ref \
        refs/heads/assistant-runtime \
        "$COMMIT" \
        "$OLD"
else
    git --git-dir="$BARE" \
        update-ref \
        refs/heads/assistant-runtime \
        "$COMMIT"
fi

rm -rf "$WORK"

printf "%s\n" "$COMMIT"
'
)"

JSON_TMP="$(mktemp "${PUBLIC_DIR}/.latest.json.XXXXXX")"
TXT_TMP="$(mktemp "${PUBLIC_DIR}/.latest.txt.XXXXXX")"

OUTPUT_END
CHAT_OUTPUT_END
