#!/usr/bin/env bash
# PoA Cluster Lens hourly step. Safe to run every hour (idempotent; fetches at most once per 50 min).
#   1. unit tests must pass, or nothing is built or deployed.
#   2. build.py: ONE keyless read-only pass (POAScan challenge index, a capped number of answer texts from the
#      minepoa.com explorer with pauses, forum introductions), then render site/{index.html,clusters.json,answers/}.
#      No API key or forum token is read or sent by any step.
#   3. If CLUSTERS_PAGES_DIR is set (checkout of poa-field-guide on its `pages` branch), copy site/ into
#      $CLUSTERS_PAGES_DIR/clusters/.  Only if CLUSTERS_PUSH=1: pull --rebase, commit, push.
# Usage: ./hourly.sh
#        CLUSTERS_PAGES_DIR=/workspace/poa/pages-checkout CLUSTERS_PUSH=1 ./hourly.sh
set -euo pipefail
cd "$(dirname "$0")"
python3 -m unittest -q tests.test_lens tests.test_review_line 2>/dev/null || { echo "cluster lens tests FAILED; not deploying" >&2; exit 1; }
python3 build.py "$@"
PAGES_DIR="${CLUSTERS_PAGES_DIR:-}"
if [ -z "$PAGES_DIR" ]; then
  echo "built ./site (no CLUSTERS_PAGES_DIR set, nothing deployed)"; exit 0
fi
[ -d "$PAGES_DIR/.git" ] || [ -f "$PAGES_DIR/.git" ] || { echo "$PAGES_DIR is not a git checkout" >&2; exit 1; }
# Token is read by askpass from a file, never printed or put on a command line.
PAGES_URL="${CLUSTERS_PAGES_URL:-https://embot-lantern@codeberg.org/embot-lantern/poa-field-guide.git}"
export GIT_ASKPASS="${GIT_ASKPASS:-/tmp/cb_askpass.sh}"
[ -x "$GIT_ASKPASS" ] || { printf '#!/bin/sh\ncase "$1" in Username*) echo embot-lantern;; *) cat /workspace/poa/codeberg-token.txt;; esac\n' > "$GIT_ASKPASS"; chmod 700 "$GIT_ASKPASS"; }
if [ "${CLUSTERS_PUSH:-0}" = "1" ]; then
  git -C "$PAGES_DIR" -c credential.helper= pull -q --rebase "$PAGES_URL" pages
fi
# Only ever touches clusters/ in the pages checkout.
rm -rf "$PAGES_DIR/clusters.new" && cp -a site "$PAGES_DIR/clusters.new" && rm -rf "$PAGES_DIR/clusters" && mv "$PAGES_DIR/clusters.new" "$PAGES_DIR/clusters"
echo "copied site/ -> $PAGES_DIR/clusters/"
if [ "${CLUSTERS_PUSH:-0}" = "1" ]; then
  stamp="$(date -u +%Y-%m-%dT%H:%MZ)"
  git -C "$PAGES_DIR" add -A clusters
  if ! git -C "$PAGES_DIR" diff --cached --quiet; then
    git -C "$PAGES_DIR" commit -q -m "clusters: hourly publish $stamp"
    if ! git -C "$PAGES_DIR" -c credential.helper= push -q "$PAGES_URL" HEAD:pages; then
      git -C "$PAGES_DIR" -c credential.helper= pull -q --rebase "$PAGES_URL" pages
      git -C "$PAGES_DIR" -c credential.helper= push -q "$PAGES_URL" HEAD:pages
    fi
    echo "pushed pages ($stamp)"
  else
    echo "pages unchanged"
  fi
fi
