#!/usr/bin/env sh
#
# git-merge-unrelated-branch - when you develop outside "official" repository,
# and your project is ready for inclusion in the mainline
#
# while Git does not support direct merges between unrelated branches,
# it can be made to comply.

set -e

if test -z "$2" || test -n "$3"; then
  echo "Usage: $(basename "$0") <repo> <branchname>" >&2
  exit 1
fi

repo="$1"
branch="$2"

git fetch "${repo}" "${branch}"

head=$(git rev-parse HEAD)
fetched=$(git rev-parse FETCH_HEAD)
headref=$(git rev-parse --symbolic-full-name HEAD)

git checkout "${fetched}" .

tree=$(git write-tree)

# shellcheck disable=SC2086,SC2250
newhead=$(echo "merged in branch '$branch' from $repo" \
  | git commit-tree $tree -p $head -p $fetched)
git-update-ref "${headref}" "${newhead}" "${head}"
git reset --hard "${headref}"
