#!/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

echo "Gitted 0.0.5 (any issues or ideas, submit to https://github.com/yegor256/gitted)"

function bash_it {
    printf '%q ' "$@" | /bin/bash -x
}

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

base=$(dirname "$0")

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

name=$1
if [ -z "${name}" ]; then
    echo "Use it like this: 'branch 42'"
    echo "Here, '42' is the name of the branch and GitHub issue number"
    exit 1
fi

bash_it "${GIT_BIN}" checkout master

"${base}/pull"

bash_it "${GIT_BIN}" status

printf "\nChecking out the %s branch...\n" "origin/${name}"
bash_it "${GIT_BIN}" checkout -b "${name}"

while true; do
    printf "\nPushing to the %s branch...\n" "origin/${name}"
    bash_it "${GIT_BIN}" push origin "${name}" && break
    if [ -n "${GITTED_TESTING}" ]; then
        exit 1
    fi
done

printf "\nSetting the upstream of the %s branch...\n" "origin/${name}"
bash_it "${GIT_BIN}" branch "--set-upstream-to=origin/${name}" "${name}"
