#!/bin/bash

set -e
set -x

readonly workdir="${1:-repro}"

# Give ourselves a fresh start.
rm -rf "$workdir"
mkdir -p "$workdir"
cd "$workdir"
git init
git branch -m main || :

# Make a root commit.
touch repro
git add repro
git commit -m root
git tag -m root "tag-prev-root"

# Create a branch and merge it according to Kitware workflow guidelines.
make_branch () {
    local branch="$1"
    readonly branch
    shift

    # Create the branch.
    git checkout -b "$branch"
    local base
    base="$( git rev-parse HEAD )"
    readonly base

    local topic
    for n in $( seq 1 2 ); do
        git checkout -b "$branch-$n" "$base"
        echo "commit $n" >> "$branch.$n.txt"
        git add "$branch.$n.txt"
        git commit -m "topic $n for $branch"
        topic="$( git rev-parse HEAD )"

        # Merge with `main`
        git checkout main
        git merge --no-edit --no-ff "$topic"

        # Merge with `branch`
        git checkout "$branch"
        git merge --no-edit --no-ff "$topic"

        # Sync with `main`
        git checkout main
        git merge --no-edit --no-ff -s ours "$branch"
        git checkout "$base"
    done

    git checkout "$branch"
    git tag -a -m "previous tag for $branch" "tag-prev-$branch"

    git checkout -b "$branch-tag" "$branch"
    echo "release prep for $branch" >> "$branch.prep.txt"
    git add "$branch.prep.txt"
    git commit -m "commit for tag preparation for $branch"
    echo "tag for $branch" >> "$branch.txt"
    git add "$branch.txt"
    git commit -m "commit for tag for $branch"
    git tag -a -m "tag for $branch" "tag-$branch"
    git checkout "$branch"
    git merge --ff-only "$branch-tag"

    # Sync with `main`
    git checkout main
    git merge --no-edit --no-ff -s ours "$branch"
    git checkout "$base"
}

make_branch release

git checkout main
describe="$( git describe )"
readonly describe

case "$describe" in
    tag-prev-*)
        echo "failed: found 'tag-prev-'"
        exit 1
        ;;
    tag-*)
        echo "success"
        :
        ;;
esac
