#!/bin/bash
# Push local_machine to Gitea on server 206.189.35.205 via Proxy (🇷🇺 ДЛЯ РФ)
# Same logic as hunabapp's script: SSH → HTTPS → Bundle
# Repo: local_machine, branch: main, target: 206.189.35.205
#
# === БЕЗОПАСНОСТЬ (SAFETY) ===
# - НЕ трогает текущую ветку, HEAD, рабочую копию, локальные коммиты.
# - НЕ выполняет: git reset, git checkout --hard, git clean, push --force.
# - Обновляет refs/remotes/origin/main только после успешного пуша.
# - --dry-run: только показать, что будет запушено.

set -e

DRY_RUN=0
[[ "${1:-}" = "--dry-run" ]] && DRY_RUN=1
if [[ "$DRY_RUN" -eq 1 ]]; then
  BRANCH="${2:-main}"
else
  BRANCH="${1:-main}"
fi

# Target: Gitea on 206.189.35.205 (mirror server)
# Optional: in ~/.ssh/config set Host gitea-mirror, HostName 206.189.35.205, User <your_user>
# Then: export GITEA_SERVER=gitea-mirror
GITEA_SSH_HOST="${GITEA_SSH_HOST:-206.189.35.205}"
GITEA_SSH_PORT="${GITEA_SSH_PORT:-2223}"
GITEA_SSH_URL="ssh://git@${GITEA_SSH_HOST}:${GITEA_SSH_PORT}/hunabgit/local_machine.git"
# Host for scp/ssh (docker exec on 206). Default: IP. Or set GITEA_SERVER=gitea-mirror if in SSH config.
SERVER="${GITEA_SERVER:-206.189.35.205}"
# HTTPS (if mirror has own URL, set GITEA_HTTPS_BASE)
GITEA_HTTPS_BASE="${GITEA_HTTPS_BASE:-https://gitea.hunab.app/hunabgit/local_machine.git}"

# Proxy (🇷🇺 ДЛЯ РФ)
PROXY_SERVER="${PROXY_SERVER:-hsites-ahau}"
PROXY_SSH_KEY="${PROXY_SSH_KEY:-$HOME/.ssh/id_ed25519}"
TARGET_SSH_KEY="${TARGET_SSH_KEY:-$HOME/.ssh/hunab_deploy_key}"

PROXY_SSH_KEY_EXPANDED="${PROXY_SSH_KEY/#\~/$HOME}"
TARGET_SSH_KEY_EXPANDED="${TARGET_SSH_KEY/#\~/$HOME}"
PROXY_CMD="ssh -i $PROXY_SSH_KEY_EXPANDED -o StrictHostKeyChecking=accept-new -W %h:%p $PROXY_SERVER"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}=== Push local_machine to Gitea via Proxy (206.189.35.205) ===${NC}"
echo -e "Branch: ${YELLOW}$BRANCH${NC}"
echo -e "Proxy: ${YELLOW}$PROXY_SERVER${NC}"
echo -e "Target: ${YELLOW}$GITEA_SSH_HOST${NC} (repo: local_machine)"
echo ""

# Must be in local_machine repo
REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || true)
if [[ ! -f "$REPO_ROOT/.gitignore" ]] || [[ ! -d "$REPO_ROOT/docs" ]]; then
  echo -e "${RED}❌ Run from local_machine repo root.${NC}"
  exit 1
fi

if ! git rev-parse --verify "origin/$BRANCH" >/dev/null 2>&1; then
  echo -e "${YELLOW}⚠️  origin/$BRANCH not found, fetching...${NC}"
  git fetch origin 2>/dev/null || true
fi

LOCAL_COMMIT=$(git rev-parse $BRANCH 2>/dev/null || echo "")
REMOTE_COMMIT=$(git rev-parse "origin/$BRANCH" 2>/dev/null || echo "")

if [ -z "$LOCAL_COMMIT" ]; then
  echo -e "${RED}❌ Error: Branch $BRANCH not found${NC}"
  exit 1
fi

if [ -z "$REMOTE_COMMIT" ]; then
  echo -e "${YELLOW}⚠️  Remote branch not found, will create it${NC}"
  REMOTE_COMMIT=""
elif [ "$LOCAL_COMMIT" = "$REMOTE_COMMIT" ]; then
  echo -e "${GREEN}✅ No commits to push${NC}"
  exit 0
fi

echo -e "Local commit:  ${BLUE}$LOCAL_COMMIT${NC}"
if [ -n "$REMOTE_COMMIT" ]; then
  echo -e "Remote commit: ${BLUE}$REMOTE_COMMIT${NC}"
fi
PENDING_COUNT=$(git rev-list --count "origin/$BRANCH..$BRANCH" 2>/dev/null || echo "?")
echo -e "Commits to push: ${BLUE}$PENDING_COUNT${NC}"
echo ""

if [[ "$DRY_RUN" -eq 1 ]]; then
  echo -e "${GREEN}✅ --dry-run: would push $PENDING_COUNT commit(s). No changes made.${NC}"
  echo "   Run without --dry-run to push: bash $0 $BRANCH"
  exit 0
fi

# Method 1: SSH via proxy
echo -e "${YELLOW}[1/3] Trying SSH push...${NC}"
CURRENT_URL=$(git remote get-url origin 2>/dev/null || echo "")

if ssh -p "$GITEA_SSH_PORT" -i "$TARGET_SSH_KEY_EXPANDED" -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new -o ProxyCommand="$PROXY_CMD" "git@$GITEA_SSH_HOST" "echo 'OK'" >/dev/null 2>&1; then
  echo -e "${GREEN}✅ SSH connection available${NC}"
  if [ -z "$CURRENT_URL" ] || [[ ! "$CURRENT_URL" =~ ssh:// ]]; then
    echo -e "${YELLOW}Switching to SSH URL...${NC}"
    git remote set-url origin "$GITEA_SSH_URL"
  fi
  GIT_SSH_COMMAND="ssh -i $TARGET_SSH_KEY_EXPANDED -p $GITEA_SSH_PORT -o ProxyCommand='$PROXY_CMD' -o StrictHostKeyChecking=accept-new"
  if GIT_SSH_COMMAND="$GIT_SSH_COMMAND" git push origin "$BRANCH" 2>&1; then
    echo -e "${GREEN}✅ Push successful via SSH!${NC}"
    exit 0
  else
    echo -e "${YELLOW}⚠️  SSH push failed, trying HTTPS...${NC}"
  fi
else
  echo -e "${YELLOW}⚠️  SSH not available, trying HTTPS...${NC}"
fi

# Method 2: HTTPS
echo -e "${YELLOW}[2/3] Trying HTTPS push...${NC}"
if [ -z "$CURRENT_URL" ] || [[ "$CURRENT_URL" =~ ssh:// ]]; then
  git remote set-url origin "$GITEA_HTTPS_BASE"
fi
git config http.postBuffer 524288000
git config http.lowSpeedLimit 0
git config http.lowSpeedTime 0
git config http.timeout 600
if command -v timeout >/dev/null 2>&1; then
  if timeout 30 git push origin "$BRANCH" 2>&1; then
    echo -e "${GREEN}✅ Push successful via HTTPS!${NC}"
    exit 0
  fi
else
  echo -e "${YELLOW}⚠️  Skipping HTTPS (no timeout cmd), using bundle...${NC}"
fi

# Method 3: Bundle
echo -e "${YELLOW}[3/3] Using bundle method...${NC}"
BUNDLE_BASE="$REMOTE_COMMIT"
if git remote get-url gitea >/dev/null 2>&1; then
  GIT_SSH_COMMAND_FETCH="ssh -i $TARGET_SSH_KEY_EXPANDED -p $GITEA_SSH_PORT -o ProxyCommand='$PROXY_CMD' -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15"
  if GIT_SSH_COMMAND="$GIT_SSH_COMMAND_FETCH" git fetch gitea "$BRANCH" 2>/dev/null; then
    GITEA_COMMIT=$(git rev-parse "gitea/$BRANCH" 2>/dev/null || echo "")
    [ -n "$GITEA_COMMIT" ] && BUNDLE_BASE="$GITEA_COMMIT" && echo -e "Bundle base (gitea/$BRANCH): ${BLUE}$GITEA_COMMIT${NC}"
  fi
fi
if [ "$BUNDLE_BASE" = "$REMOTE_COMMIT" ]; then
  echo -e "${YELLOW}Querying Gitea refs/heads/$BRANCH on server...${NC}"
  GITEA_COMMIT=$(ssh -i "$TARGET_SSH_KEY_EXPANDED" -o ProxyCommand="$PROXY_CMD" "$SERVER" "docker exec gitea sh -c 'cd /data/git/repositories/hunabgit/local_machine.git && git rev-parse refs/heads/$BRANCH'" 2>/dev/null || echo "")
  if [ -n "$GITEA_COMMIT" ]; then
    BUNDLE_BASE="$GITEA_COMMIT"
    echo -e "Bundle base (Gitea on server): ${BLUE}$GITEA_COMMIT${NC}"
  else
    echo -e "${YELLOW}⚠️  Could not get server ref (repo may be new). Using full branch bundle.${NC}"
  fi
fi

mkdir -p "$REPO_ROOT/temp"
BUNDLE_FILE="$REPO_ROOT/temp/gitea-push-${BRANCH}-$(date +%s).bundle"
echo "Creating bundle: $BUNDLE_FILE"
if [ -n "$BUNDLE_BASE" ] && ! git cat-file -e "$BUNDLE_BASE^{commit}" 2>/dev/null; then
  echo -e "${YELLOW}⚠️  Server commit not in local repo. Creating full branch bundle.${NC}"
  BUNDLE_BASE=""
fi
BUNDLE_FAILED=0
if [ -n "$BUNDLE_BASE" ]; then
  git bundle create "$BUNDLE_FILE" "$BUNDLE_BASE..$BRANCH" || BUNDLE_FAILED=1
else
  git bundle create "$BUNDLE_FILE" "$BRANCH" || BUNDLE_FAILED=1
fi
if [ "$BUNDLE_FAILED" -eq 1 ]; then
  echo -e "${RED}❌ Bundle creation failed.${NC}"
  exit 1
fi

BUNDLE_SIZE=$(du -h "$BUNDLE_FILE" | cut -f1)
echo "Bundle size: $BUNDLE_SIZE"
echo "Copying bundle to server via proxy..."
scp -i "$TARGET_SSH_KEY_EXPANDED" -o ProxyCommand="$PROXY_CMD" "$BUNDLE_FILE" "$SERVER:/tmp/$(basename "$BUNDLE_FILE")" || {
  echo -e "${RED}❌ Failed to copy bundle.${NC}"
  echo -e "   Check: GITEA_SERVER=$SERVER (e.g. 206.189.35.205 or Host from ~/.ssh/config), proxy $PROXY_SERVER reachable."
  rm -f "$BUNDLE_FILE"
  exit 1
}

NEW_COMMIT=$(git bundle list-heads "$BUNDLE_FILE" | grep "^$BRANCH" | cut -d" " -f1)
[ -z "$NEW_COMMIT" ] && NEW_COMMIT=$(git bundle list-heads "$BUNDLE_FILE" | head -1 | cut -d" " -f1)
if [ -z "$NEW_COMMIT" ]; then
  echo -e "${RED}❌ Could not find commit in bundle${NC}"
  rm -f "$BUNDLE_FILE"
  exit 1
fi

BUNDLE_BASENAME=$(basename "$BUNDLE_FILE")
APPLY_OUT=$(mktemp 2>/dev/null || echo "/tmp/gitea-apply-$$.out")
if ! ssh -i "$TARGET_SSH_KEY_EXPANDED" -o ProxyCommand="$PROXY_CMD" "$SERVER" "docker cp /tmp/$BUNDLE_BASENAME gitea:/tmp/push-bundle.bundle && docker exec -e BRANCH='$BRANCH' -e NEW_COMMIT='$NEW_COMMIT' gitea sh -c 'cd /data/git/repositories/hunabgit/local_machine.git && git bundle unbundle /tmp/push-bundle.bundle && git update-ref refs/heads/\$BRANCH \$NEW_COMMIT && rm -f /tmp/push-bundle.bundle' && rm -f /tmp/$BUNDLE_BASENAME" 2>"$APPLY_OUT"; then
  echo -e "${RED}❌ Failed to apply bundle${NC}"
  [ -s "$APPLY_OUT" ] && cat "$APPLY_OUT"
  echo -e "${YELLOW}→ Ensure repo exists on 206: Gitea UI → New Repository → local_machine (empty).${NC}"
  echo "  Then: git remote add gitea $GITEA_SSH_URL && git fetch gitea $BRANCH"
  echo "  And re-run: bash scripts/deployment/gitea/git-push-gitea-via-proxy.sh $BRANCH"
  rm -f "$APPLY_OUT" "$BUNDLE_FILE"
  exit 1
fi
rm -f "$APPLY_OUT" "$BUNDLE_FILE"

if [ "$NEW_COMMIT" = "$LOCAL_COMMIT" ]; then
  echo -e "${YELLOW}Updating local tracking ref (origin/$BRANCH)...${NC}"
  git update-ref "refs/remotes/origin/$BRANCH" "$NEW_COMMIT" 2>/dev/null || true
fi

echo -e "${GREEN}✅ Push completed via bundle!${NC}"
echo -e "   Commit: ${BLUE}$NEW_COMMIT${NC}"
