#!/bin/bash
# Mirrors our Forgejo repo into GitHub. Best-effort: if the push fails (flaky
# KZ TCP to github.com), the next tick will retry.
set -euo pipefail

MIRROR_DIR="/opt/food-market-data/forgejo/mirror"
FORGEJO_URL="http://127.0.0.1:3000/nns/food-market.git"
GITHUB_URL="https://github.com/nurdotnet/food-market.git"
GITHUB_TOKEN_FILE="/etc/food-market/github-mirror-token"  # 40-char PAT with repo scope
LOG_FILE="/var/log/food-market-forgejo-mirror.log"

log() { printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >> "$LOG_FILE"; }

if [[ ! -f $GITHUB_TOKEN_FILE ]]; then
  log "token file $GITHUB_TOKEN_FILE missing — skipping mirror push"
  exit 0
fi
TOKEN=$(tr -d '\n' < "$GITHUB_TOKEN_FILE")

if [[ ! -d $MIRROR_DIR/objects ]]; then
  log "bootstrap: cloning $FORGEJO_URL → $MIRROR_DIR"
  rm -rf "$MIRROR_DIR"
  git clone --mirror "$FORGEJO_URL" "$MIRROR_DIR" >> "$LOG_FILE" 2>&1
fi

cd "$MIRROR_DIR"

# Pull latest from Forgejo (source of truth).
if ! git remote update --prune >> "$LOG_FILE" 2>&1; then
  log "forgejo fetch failed — aborting this tick"
  exit 0
fi

# Push everything to GitHub, timeout generously (big pushes on flaky link).
GIT_HTTP_LOW_SPEED_LIMIT=1000 \
GIT_HTTP_LOW_SPEED_TIME=60 \
timeout 300 git push --prune "https://x-access-token:$TOKEN@github.com/nurdotnet/food-market.git" \
  '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*' >> "$LOG_FILE" 2>&1 \
  && log "pushed to github ok" \
  || log "github push failed (exit=$?), will retry next tick"
