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

set -e -o pipefail

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

if [ -n "${GITTED_VERBOSE}" ]; 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

echo "Staging local changes..."
"${GIT_BIN}" add .

stashed=no
if ! git diff --quiet || ! git diff --cached --quiet; then
    trap "echo 'Applying the changes back...' && \${GIT_BIN} stash apply" EXIT
    echo "Stashing local changes..."
    "${GIT_BIN}" stash
    stashed=yes
fi

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

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