#!/bin/ash
#
# Trigger Gitea pull-mirror sync (one repo or all). For BE cron / FE post-receive hook.
#
# Usage:
#   sudo ./gitea_sync_mirror.sh android_cast
#   sudo ./gitea_sync_mirror.sh android_cast libvpx opus
#   sudo ./gitea_sync_mirror.sh --all
#
set -eu

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=gitea_ini.sh
. "$SCRIPT_DIR/gitea_ini.sh"
# shellcheck source=gitea_mirror_lib.sh
. "$SCRIPT_DIR/gitea_mirror_lib.sh"

GITEA_OWNER="${GITEA_OWNER:-${GITEA_ORG:-AndroidCast}}"

log() { printf '[gitea-sync] %s\n' "$*"; }
warn() { printf '[gitea-sync] WARN: %s\n' "$*" >&2; }
die() { printf '[gitea-sync] ERROR: %s\n' "$*" >&2; exit 1; }

gitea_load_config || exit 1
gitea_ensure_cli_access || exit 1

_sync_all=0
_repos=""

while [ $# -gt 0 ]; do
  case "$1" in
    -h|--help)
      sed -n '2,10p' "$0"
      exit 0
      ;;
    --all) _sync_all=1; shift ;;
    -*) die "unknown option: $1" ;;
    *) _repos="$_repos $1"; shift ;;
  esac
done

if [ "$_sync_all" -eq 1 ]; then
  log "sync all mirrors via gitea admin repo-sync-mirrors"
  gitea_cli "admin" "repo-sync-mirrors"
  exit $?
fi

if [ -z "$(echo "$_repos" | tr -d ' ')" ]; then
  _repos="android_cast"
fi

_fail=0
for _repo in $_repos; do
  log "mirror-sync $GITEA_OWNER/$_repo"
  if gitea_sync_mirror_api "$GITEA_OWNER" "$_repo"; then
    log "  OK"
  else
    warn "  FAILED"
    _fail=1
  fi
done

exit "$_fail"
