#!/bin/bash
# SPDX-FileCopyrightText: Copyright (c) 2025 Yegor Bugayenko
# SPDX-License-Identifier: MIT

set -ex -o pipefail

if [ -n "${GITTED_TESTING}" ]; then
    set -x
fi

if ! git rev-parse --git-dir > /dev/null 2>&1; then
    echo "Oops, this is not a Git repository"
    exit 1
fi

if [ -z "${GIT_BIN}" ]; then
  GIT_BIN=git
fi

branch=$("${GIT_BIN}" symbolic-ref HEAD --short)

if ! "${GIT_BIN}" rev-parse --abbrev-ref --symbolic-full-name '@{u}' >/dev/null 2>&1; then
  echo "The upstream is not configured for the '${branch}' branch, setting it to 'origin/${branch}'"
  "${GIT_BIN}" fetch
  "${GIT_BIN}" branch "--set-upstream-to=origin/${branch}" "${branch}"
fi

if [ -e .git/modules ]; then
  echo "A few submodules need to be pulled first..."
  while true; do
    "${GIT_BIN}" submodule update --remote && break
    if [ -n "${GITTED_TESTING}" ]; then
      exit 1
    fi
  done
fi

trap "echo 'Applying the changes back...' && \${GIT_BIN} stash apply" EXIT
echo "Staging local changes..."
"${GIT_BIN}" add .
echo "Stashing local changes..."
"${GIT_BIN}" stash
while true; do
  echo "Pulling..."
  "${GIT_BIN}" pull && break
  if [ -n "${GITTED_TESTING}" ]; then
    exit 1
  fi
done
trap - EXIT
echo "Trying to apply the changes back..."
"${GIT_BIN}" stash apply

# Then, we should pull+merge from upstream...
