#!/usr/bin/env bash
# Setup local_machine as a git repo and push to Gitea (gitea.hunab.app).
# Usage:
#   1. Create repo on Gitea (once): UI https://gitea.hunab.app -> New Repository "local_machine"
#      OR: GITEA_TOKEN=xxx bash scripts/deployment/gitea/setup-and-push.sh --create-only
#   2. Push: bash scripts/deployment/gitea/setup-and-push.sh

set -e
GITEA_HOST="${GITEA_HOST:-https://gitea.hunab.app}"
GITEA_USER="${GITEA_USER:-hunabgit}"
REPO_NAME="local_machine"
REMOTE_URL_HTTPS="${GITEA_HOST}/${GITEA_USER}/${REPO_NAME}.git"
# SSH port 2223 (see docs/git/GITEA_COMPLETE_GUIDE.md)
REMOTE_URL_SSH="ssh://git@gitea.hunab.app:2223/${GITEA_USER}/${REPO_NAME}.git"

# Must run from repo root (local_machine)
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
if [[ ! -f "$ROOT/.gitignore" ]] || [[ ! -d "$ROOT/docs" ]]; then
  echo "Run from local_machine root. Current: $ROOT"
  exit 1
fi
cd "$ROOT"

# --- Create repo via API (optional) ---
if [[ "$1" == "--create-only" ]]; then
  if [[ -z "$GITEA_TOKEN" ]]; then
    echo "Create repo manually: $GITEA_HOST -> New Repository -> Name: $REPO_NAME"
    echo "Or set GITEA_TOKEN and run again with --create-only to create via API."
    exit 0
  fi
  echo "Creating repository $REPO_NAME..."
  curl -s -X POST "${GITEA_HOST}/api/v1/user/repos" \
    -H "Authorization: token $GITEA_TOKEN" \
    -H "Content-Type: application/json" \
    -d "{\"name\":\"$REPO_NAME\",\"description\":\"Local machine docs and scripts\",\"private\":false,\"auto_init\":false}" \
    && echo "" && echo "Repo created. Run without --create-only to push."
  exit 0
fi

# --- Init git if needed ---
if [[ ! -d .git ]]; then
  git init
  git branch -M main
  echo "Git initialized (branch main)."
fi

# --- Remote ---
if ! git remote get-url origin &>/dev/null; then
  # Prefer SSH (port 2223) — надёжнее из РФ
  if command -v ssh &>/dev/null && ssh -o BatchMode=yes -o ConnectTimeout=5 -p 2223 git@gitea.hunab.app 2>/dev/null; then
    git remote add origin "$REMOTE_URL_SSH"
    echo "Remote origin set (SSH, port 2223)."
  else
    git remote add origin "$REMOTE_URL_HTTPS"
    echo "Remote origin set (HTTPS). From РФ: use SSH (port 2223) or proxy — see docs/git/GITEA_COMPLETE_GUIDE.md"
  fi
fi

# --- Commit and push ---
git add -A
if git diff --cached --quiet; then
  echo "Nothing to commit."
else
  git commit -m "Initial commit: local_machine docs and scripts"
  echo "Committed."
fi

echo "Pushing to $GITEA_USER/$REPO_NAME..."
if git push -u origin main 2>/dev/null; then
  echo "Done. Repo: $GITEA_HOST/$GITEA_USER/$REPO_NAME"
else
  echo "Push failed (e.g. timeout from РФ). Try:"
  echo "  SSH: git remote set-url origin $REMOTE_URL_SSH  # port 2223"
  echo "       git push -u origin main"
  echo "  Or use bundle method from docs/git/GITEA_COMPLETE_GUIDE.md"
  exit 1
fi
