#!/bin/ash
#
# Set default branch (next) on Gitea repos for UI clone/browse defaults.
#
# Usage:
#   sudo ./gitea_set_default_branch.sh
#   GITEA_DEFAULT_BRANCH=next GITEA_OWNER=AndroidCast sudo ./gitea_set_default_branch.sh
#
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}}"
GITEA_DEFAULT_BRANCH="${GITEA_DEFAULT_BRANCH:-next}"
# Space-separated repo names; empty = all listed under owner.
GITEA_REPO_NAMES="${GITEA_REPO_NAMES:-}"

log() { printf '[gitea-default-branch] %s\n' "$*"; }
warn() { printf '[gitea-default-branch] WARN: %s\n' "$*" >&2; }

gitea_load_config || exit 1
gitea_ensure_cli_access || exit 1

_repos=""
if [ -n "$GITEA_REPO_NAMES" ]; then
  _repos="$GITEA_REPO_NAMES"
else
  _repos="$(gitea_list_repos_api "$GITEA_OWNER" 2>/dev/null)" || _repos=""
fi

if [ -z "$(echo "$_repos" | tr -d ' ')" ]; then
  warn "no repos under $GITEA_OWNER"
  exit 1
fi

_ok=0
_fail=0
for _repo in $_repos; do
  [ -n "$_repo" ] || continue
  if gitea_repo_set_default_branch_api "$GITEA_OWNER" "$_repo" "$GITEA_DEFAULT_BRANCH"; then
    log "$GITEA_OWNER/$_repo -> default branch $GITEA_DEFAULT_BRANCH"
    _ok=$((_ok + 1))
  else
    warn "failed $GITEA_OWNER/$_repo (branch $GITEA_DEFAULT_BRANCH may not exist yet — sync mirror first)"
    _fail=$((_fail + 1))
  fi
done

log "done ok=$_ok fail=$_fail"
[ "$_fail" -eq 0 ]
