#!/bin/bash

# shellcheck shell=bash

# Rebase from primary
bridge_rebase_from_primary() {
  shift || true
  wt=""; br=""
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --worktree) wt="$2"; shift 2;;
      --branch) br="$2"; shift 2;;
      *) shift;;
    esac
  done
  if [[ -z "$wt" || -z "$br" ]]; then
    json_error "--worktree and --branch required"; return 1
  fi
  if ! git_require_repo_root >/dev/null 2>&1; then
    json_error "Not a git repository"; return 1
  fi
  pr="$(git_primary_branch || true)"
  if [[ -z "$pr" ]]; then
    json_object \
      "ok:b=false" \
      "operation:s=rebase-from-primary" \
      "error_type:s=no_primary_detected" \
      "message:s=Could not detect primary branch"
    return 0
  fi
  LOGS=""; append() { LOGS+="$1"$'\n'; }
  append "$ git -C $wt fetch origin --prune"
  append "$(git_fetch_prune "$wt")"
  if git -C "$wt" rev-parse --verify "origin/$pr" >/dev/null 2>&1; then
    upstream="origin/$pr"
  else
    upstream="$pr"
  fi
  append "$ git -C $wt rebase $upstream"
  set +e
  out="$(git_rebase_onto "$wt" "$upstream")"
  rc=$?
  set -e
  append "$out"
  summary="$(git_error_summary "$out")"
  if [[ -z "$summary" ]]; then
    summary="Rebase conflict or error"
  fi
  logs_json="$(json_array_from_lines "$LOGS")"
  if [[ $rc -eq 0 ]]; then
    result="rebased"
    if echo "$out" | grep -qi 'up[- ]to[- ]date'; then result="up_to_date"; fi
    json_object \
      "ok:b=true" \
      "operation:s=rebase-from-primary" \
      "primary:s=$pr" \
      "target_branch:s=$br" \
      "target_path:s=$wt" \
      "result:s=$result" \
      "logs:j=$logs_json"
  else
    json_object \
      "ok:b=false" \
      "operation:s=rebase-from-primary" \
      "error_type:s=rebase_conflict" \
      "message:s=$summary" \
      "primary:s=$pr" \
      "target_branch:s=$br" \
      "target_path:s=$wt" \
      "logs:j=$logs_json"
  fi
}
