#!/usr/bin/env bash
# =============================================================================
# push-to-gitea.sh — Push current branch to local Gitea via bore tunnel
#
# Usage:
#   bash scripts/push-to-gitea.sh [PORT]
#
# PORT is the bore.pub port shown when bore starts on your Mac:
#   bore local 3000 --to bore.pub
#   → "listening at bore.pub:NNNNN"
#
# If PORT is supplied it is saved to .bore-port for future calls.
# If PORT is omitted the script tries (in order):
#   1. .bore-port file in repo root
#   2. Port embedded in the current 'gitea' remote URL
# =============================================================================
set -euo pipefail

GITEA_HOST="bore.pub"
GITEA_USER="${GITEA_USER:-replit}"

# ─── Load token ───────────────────────────────────────────────────────────────
# Token is never hard-coded. Resolution order:
#   1. GITEA_TOKEN env var (export before running, or set in shell profile)
#   2. .gitea-credentials file in repo root (gitignored, one line: the token)
REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
CREDS_FILE="$REPO_ROOT/.gitea-credentials"

if [[ -z "${GITEA_TOKEN:-}" && -f "$CREDS_FILE" ]]; then
  GITEA_TOKEN="$(tr -d '[:space:]' < "$CREDS_FILE")"
fi

if [[ -z "${GITEA_TOKEN:-}" ]]; then
  echo -e "\033[0;31m[error]\033[0m GITEA_TOKEN is not set." >&2
  echo "" >&2
  echo "  Set it in one of two ways:" >&2
  echo "" >&2
  echo "  a) Export in your shell:" >&2
  echo "       export GITEA_TOKEN=<your-token>" >&2
  echo "" >&2
  echo "  b) Save to a gitignored credentials file:" >&2
  echo "       echo <your-token> > .gitea-credentials" >&2
  echo "" >&2
  echo "  Get your token from: http://bore.pub:<PORT>/user/settings/applications" >&2
  exit 1
fi

BORE_PORT_FILE="$REPO_ROOT/.bore-port"

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'
info() { echo -e "${CYAN}[gitea]${NC} $*"; }
ok()   { echo -e "${GREEN}[ok]${NC}    $*"; }
warn() { echo -e "${YELLOW}[warn]${NC}  $*"; }
die()  { echo -e "${RED}[error]${NC} $*" >&2; exit 1; }

# ─── 1. Resolve bore port ────────────────────────────────────────────────────

PORT=""

if [[ -n "${1:-}" ]]; then
  PORT="$1"
  echo "$PORT" > "$BORE_PORT_FILE"
  info "Port $PORT saved to .bore-port for future calls."

elif [[ -f "$BORE_PORT_FILE" ]]; then
  PORT="$(tr -d '[:space:]' < "$BORE_PORT_FILE")"
  info "Using port $PORT from .bore-port"

else
  # Fall back to whatever port is currently in the gitea remote URL
  CURRENT_REMOTE="$(git -C "$REPO_ROOT" remote get-url gitea 2>/dev/null || true)"
  if [[ "$CURRENT_REMOTE" =~ :([0-9]{4,6})/ ]]; then
    PORT="${BASH_REMATCH[1]}"
    warn "No .bore-port file — trying last-known port $PORT from git remote."
  fi
fi

if [[ -z "$PORT" ]]; then
  die "Cannot determine bore port.

  Start bore on your Mac:
    bore local 3000 --to bore.pub
    → note the port shown (e.g. 61049)

  Then either:
    Pass the port once:   bash scripts/push-to-gitea.sh <PORT>
    Or save it manually:  echo <PORT> > .bore-port"
fi

# ─── 2. Verify Gitea is reachable ────────────────────────────────────────────

GITEA_BASE="http://${GITEA_HOST}:${PORT}"
info "Checking Gitea at ${GITEA_BASE} …"

if ! curl -sf --max-time 6 "${GITEA_BASE}/api/v1/version" -o /dev/null 2>/dev/null; then
  die "Gitea is not reachable at ${GITEA_BASE}.

  If the bore port changed, pass the new port:
    bash scripts/push-to-gitea.sh <NEW_PORT>

  If bore is not running on your Mac, start it:
    bore local 3000 --to bore.pub"
fi

ok "Gitea reachable at ${GITEA_BASE}"

# ─── 3. Detect repo and branch ───────────────────────────────────────────────

# Prefer the repo name from the existing gitea remote URL — the Replit
# workspace directory name ('workspace') does not match the Gitea repo name.
EXISTING_REMOTE="$(git -C "$REPO_ROOT" remote get-url gitea 2>/dev/null || true)"
if [[ "$EXISTING_REMOTE" =~ /([^/]+)\.git$ ]]; then
  REPO_NAME="${BASH_REMATCH[1]}"
else
  REPO_NAME="$(basename "$REPO_ROOT")"
fi

BRANCH="$(git -C "$REPO_ROOT" rev-parse --abbrev-ref HEAD)"

if [[ "$BRANCH" == "HEAD" ]]; then
  die "Detached HEAD state — check out a branch before pushing."
fi

REMOTE_URL="${GITEA_BASE}/${GITEA_USER}/${REPO_NAME}.git"
REMOTE_URL_WITH_CREDS="http://${GITEA_USER}:${GITEA_TOKEN}@${GITEA_HOST}:${PORT}/${GITEA_USER}/${REPO_NAME}.git"

info "Repo:   ${REPO_NAME}"
info "Branch: ${BRANCH}"

# ─── 4. Update (or add) the gitea remote ─────────────────────────────────────

if git -C "$REPO_ROOT" remote get-url gitea &>/dev/null; then
  git -C "$REPO_ROOT" remote set-url gitea "$REMOTE_URL_WITH_CREDS"
else
  git -C "$REPO_ROOT" remote add gitea "$REMOTE_URL_WITH_CREDS"
  info "Added 'gitea' remote."
fi

# ─── 5. Push ─────────────────────────────────────────────────────────────────

info "Pushing ${BRANCH} → gitea …"
echo ""

if git -C "$REPO_ROOT" push gitea "HEAD:${BRANCH}"; then
  echo ""
  ok "Pushed ${BRANCH} successfully."
  echo ""
  echo "  Branch:  ${GITEA_BASE}/${GITEA_USER}/${REPO_NAME}/src/branch/${BRANCH}"
  echo "  Open PR: ${GITEA_BASE}/${GITEA_USER}/${REPO_NAME}/compare/main...${BRANCH}"
  echo ""
else
  EXIT_CODE=$?
  echo ""
  die "git push failed (exit ${EXIT_CODE}). See error above."
fi
