#!/bin/bash
set -euo pipefail

if [ -n "${REPO_ROOT:-}" ] && [ -d "$REPO_ROOT/.git" ]; then
  cd "$REPO_ROOT"
fi

if [ ! -d .git ]; then
  if repo_root=$(git rev-parse --show-toplevel 2>/dev/null); then
    cd "$repo_root"
  elif [ -d "$HOME/Xslt/.git" ]; then
    cd "$HOME/Xslt"
  else
    echo "Repositorio Git nao encontrado. Entre no repo ou defina REPO_ROOT." >&2
    exit 1
  fi
fi

branch="${GIT_BRANCH:-}"
if [ -z "$branch" ]; then
  branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)
  [ "$branch" = "HEAD" ] && branch=""
fi
if [ -z "$branch" ]; then
  branch=$(git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null | sed 's|^origin/||' || true)
fi
if [ -z "$branch" ]; then
  branch="main"
fi

echo "Atualizando branch $branch em $(pwd)"
git fetch origin "$branch"

git -c rebase.autoStash=true pull --rebase origin "$branch"

echo "Atualizacao concluida."
