#!/bin/ash
#
# Why Gitea pull mirrors stopped syncing (one-time migrate vs cron vs queue).
#
# Usage:
#   sudo ./gitea_diagnose_mirror_sync.sh
#   GITEA_OWNER=AndroidCast GITEA_REPO=android_cast sudo ./gitea_diagnose_mirror_sync.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_REPO="${GITEA_REPO:-android_cast}"
GITEA_MIRROR_URL="${GITEA_MIRROR_URL:-git://10.7.0.10/android_cast}"

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

json_bool() {
  _json="$1"
  _key="$2"
  printf '%s' "$_json" | tr -d '\n' | grep -o "\"$_key\":[^,}]*" | head -1 | sed 's/.*://;s/ //g'
}

json_str() {
  _json="$1"
  _key="$2"
  printf '%s' "$_json" | tr -d '\n' | grep -o "\"$_key\":\"[^\"]*\"" | head -1 | sed 's/.*:"//;s/"$//'
}

gitea_load_config || exit 1
gitea_ensure_cli_access || exit 1

log "ini=$GITEA_APP_INI"
log "repo=$GITEA_OWNER/$GITEA_REPO  upstream=$GITEA_MIRROR_URL"

# --- upstream reachability ---
if git ls-remote "$GITEA_MIRROR_URL" HEAD >/dev/null 2>&1; then
  log "upstream reachable from this host (git ls-remote OK)"
else
  warn "upstream NOT reachable — scheduled pull mirrors will fail (check git daemon, ALLOW_LOCALNETWORKS)"
fi

# --- repo mirror flags (API) ---
_meta="$(gitea_repo_get_api "$GITEA_OWNER" "$GITEA_REPO" 2>/dev/null)" || _meta=""
if [ -z "$_meta" ]; then
  warn "could not read repo via API"
else
  _mirror="$(json_bool "$_meta" "mirror")"
  _interval="$(json_str "$_meta" "mirror_interval")"
  _default="$(json_str "$_meta" "default_branch")"
  _updated="$(json_str "$_meta" "updated_at")"
  log "api mirror=$_mirror  mirror_interval=$_interval  default_branch=$_default  updated_at=$_updated"
  if [ "$_mirror" != "true" ]; then
    warn "repo is NOT a pull mirror — only the initial push happened; auto-sync will never run"
    warn "fix: delete $GITEA_OWNER/$GITEA_REPO in Gitea UI, re-run:"
    warn "  sudo ./gitea_attach_remote.sh $GITEA_MIRROR_URL"
    warn "  (API migrate must succeed — not git-push fallback)"
  fi
fi

# --- app.ini mirror cron hints ---
for _ini in "$GITEA_APP_INI" /etc/gitea/app.ini; do
  [ -r "$_ini" ] || continue
  log "config $_ini:"
  awk '
    /^\[/ { sec = $0; gsub(/^\[|\]$/, "", sec) }
    /^(ENABLED|SCHEDULE|MIN_INTERVAL|DEFAULT_INTERVAL|PULL_LIMIT|ALLOW_LOCALNETWORKS)/ {
      print "  " sec " " $0
    }
  ' "$_ini" | grep -E 'cron\.update_mirrors|^\s*\[mirror\]|migrations' || true
done

# --- sqlite mirror row (next_update) if available ---
if command -v sqlite3 >/dev/null 2>&1; then
  _db="${GITEA_DB_PATH:-}"
  [ -n "$_db" ] || _db="$GITEA_APP_DATA/gitea.db"
  [ -r "$_db" ] || _db="/var/lib/gitea/db/gitea.db"
  if [ -r "$_db" ]; then
    log "mirror table (repo_id, interval, next_update_unix, updated_unix):"
    sqlite3 -header -column "$_db" "
      SELECT m.repo_id, m.interval, m.next_update_unix, m.updated_unix, r.name
      FROM mirror m
      JOIN repository r ON r.id = m.repo_id
      WHERE r.lower_name = lower('$GITEA_REPO')
      LIMIT 5;
    " 2>/dev/null || warn "mirror SQL query failed"
  fi
fi

# --- gitea.log mirror errors ---
for _logf in "$GITEA_LOG_ROOT/gitea.log" /var/log/gitea/gitea.log; do
  [ -r "$_logf" ] || continue
  log "recent mirror errors in $_logf:"
  grep -E 'mirror|already in queue|update_mirrors' "$_logf" 2>/dev/null | tail -n 8 || true
  break
done

cat <<EOF

Quick fixes:
  1) Manual sync now:
       sudo ./gitea_sync_mirror.sh $GITEA_REPO
  2) Sync all mirrors:
       sudo -u gitea gitea -c $GITEA_APP_INI admin repo-sync-mirrors
  3) Stuck queue ("already in queue"): Gitea Admin -> Monitor -> Queues -> Remove All (mirror)
  4) Ensure app.ini:
       [cron.update_mirrors]
       ENABLED = true
       SCHEDULE = @every 10m
       RUN_AT_START = true
     then: sudo rc-service gitea restart
  5) FE push trigger: fe-android_cast-post-receive.example

EOF
