#!/usr/bin/env bash
set -euo pipefail

# === Config por defecto (podés cambiarlas por flags) ===
SRC_REPO_URL="https://github.com/LACOMPANIADIGITAL/cd-system.git"
SRC_BRANCH="cd-system"     # rama origen en el repo maestro
LOCAL_BRANCH="cd-system"   # rama destino en ESTE repo
TEMP_REMOTE="cd-system-src"
DO_PUSH="yes"              # yes | no
SHALLOW="no"               # yes | no  (si 'yes', solo último snapshot)

usage() {
  cat <<EOF
Uso: $(basename "$0") [opciones]
  --src-url URL         URL del repo maestro (default: $SRC_REPO_URL)
  --src-branch NAME     Rama en el repo maestro (default: $SRC_BRANCH)
  --local-branch NAME   Rama local a actualizar (default: $LOCAL_BRANCH)
  --push yes|no         Hacer push a origin luego (default: $DO_PUSH)
  --shallow yes|no      Fetch shallow (solo último snapshot) (default: $SHALLOW)
  -h, --help            Mostrar ayuda

Ejemplos:
  $(basename "$0")
  $(basename "$0") --push no
  $(basename "$0") --src-url https://github.com/LACOMPANIADIGITAL/otro.git --src-branch cd-system
EOF
}

# Parseo de flags
while [[ $# -gt 0 ]]; do
  case "$1" in
    --src-url)       SRC_REPO_URL="$2"; shift 2 ;;
    --src-branch)    SRC_BRANCH="$2"; shift 2 ;;
    --local-branch)  LOCAL_BRANCH="$2"; shift 2 ;;
    --push)          DO_PUSH="$2"; shift 2 ;;
    --shallow)       SHALLOW="$2"; shift 2 ;;
    -h|--help)       usage; exit 0 ;;
    *) echo "Opción desconocida: $1"; usage; exit 1 ;;
  esac
done

echo ">> Verificando repo Git..."
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || { echo "No es un repo Git"; exit 1; }

echo ">> Cambiando a rama destino: $LOCAL_BRANCH"
if git show-ref --verify --quiet "refs/heads/$LOCAL_BRANCH"; then
  git switch "$LOCAL_BRANCH"
else
  echo "   Rama '$LOCAL_BRANCH' no existe. Creándola vacía..."
  git switch --orphan "$LOCAL_BRANCH"
  git reset --hard
fi

# Tag de backup antes de reemplazar
TS="$(date +%Y%m%d-%H%M%S)"
BACKUP_TAG="backup/${LOCAL_BRANCH}-${TS}"
echo ">> Creando tag de backup: $BACKUP_TAG"
git tag -f "$BACKUP_TAG" || true

echo ">> Agregando/actualizando remoto temporal: $TEMP_REMOTE"
if git remote get-url "$TEMP_REMOTE" >/dev/null 2>&1; then
  git remote set-url "$TEMP_REMOTE" "$SRC_REPO_URL"
else
  git remote add "$TEMP_REMOTE" "$SRC_REPO_URL"
fi

echo ">> Fetch de $SRC_BRANCH desde $SRC_REPO_URL"
if [[ "$SHALLOW" == "yes" ]]; then
  git fetch --depth=1 "$TEMP_REMOTE" +refs/heads/$SRC_BRANCH:refs/remotes/$TEMP_REMOTE/$SRC_BRANCH
else
  git fetch "$TEMP_REMOTE" +refs/heads/$SRC_BRANCH:refs/remotes/$TEMP_REMOTE/$SRC_BRANCH
fi

echo ">> Reemplazando contenido e historial de '$LOCAL_BRANCH'"
git reset --hard "refs/remotes/$TEMP_REMOTE/$SRC_BRANCH"

echo ">> Removiendo remoto temporal"
git remote remove "$TEMP_REMOTE" || true

if [[ "$DO_PUSH" == "yes" ]]; then
  echo ">> Pusheando '$LOCAL_BRANCH' a origin (force)"
  git push origin "$LOCAL_BRANCH" --force
  echo ">> Subiendo tag de backup: $BACKUP_TAG"
  git push origin "$BACKUP_TAG" || true
else
  echo ">> Push desactivado (--push no). Recordatorio:"
  echo "   git push origin $LOCAL_BRANCH --force"
  echo "   git push origin $BACKUP_TAG"
fi

echo "✅ Listo. '$LOCAL_BRANCH' actualizado desde '$SRC_BRANCH' del maestro."
