#!/usr/bin/env bash
# Build + push the site image to the public Gitea registry using rootless buildah.
# Bootstrap path for M1-M4 (before the Gitea Actions runner exists in M5).
#
# Usage:  scripts/build-image.sh [push]
#   (no arg) -> build only
#   push     -> build then push, and print the pushed digest to pin in home-ops
#
# Requires: buildah (rootless) on the host, and `buildah login` to the registry
# for the push step (anonymous pull, authenticated push).
set -euo pipefail

REGISTRY="${REGISTRY:-git.bztmon.com}"
IMAGE="${IMAGE:-jwright/bztmon-site}"
REF="${REGISTRY}/${IMAGE}"
# Per-user digest file so manual (odysseus) and CI (gitea-runner) runs never collide in /tmp.
DIGEST_FILE="${DIGEST_FILE:-${TMPDIR:-/tmp}/bztmon-site-$(id -un).digest}"

cd "$(dirname "$0")/.."

# Tag with the short git sha when available, else 'dev'.
TAG="$(git rev-parse --short HEAD 2>/dev/null || echo dev)"

# Retry helper — base-image blob pulls from docker.io/ghcr.io occasionally 502/rate-limit.
retry() {
  local n=0 max=4
  until "$@"; do
    n=$((n+1)); [ "$n" -ge "$max" ] && { echo ">> failed after ${max} attempts: $*" >&2; return 1; }
    echo ">> attempt ${n} failed, retrying in $((n*8))s..." >&2; sleep $((n*8))
  done
}

echo ">> building ${REF}:${TAG}"
retry buildah build --retry 3 --retry-delay 5s --layers --build-arg GIT_SHA="${TAG}" -t "${REF}:${TAG}" -t "${REF}:latest" .

if [[ "${1:-}" == "push" ]]; then
  echo ">> pushing ${REF}:${TAG}"
  retry buildah push --digestfile "${DIGEST_FILE}" "${REF}:${TAG}"
  retry buildah push "${REF}:latest"
  DIGEST="$(cat "${DIGEST_FILE}")"
  echo
  echo ">> pin this in home-ops kubernetes/apps/bztmon-site/bztmon-site.yaml:"
  echo "   image: ${REF}:${TAG}@${DIGEST}"
else
  echo ">> built (not pushed). Re-run with: scripts/build-image.sh push"
fi
