#!/usr/bin/env bash
set -euEx

[[ $# = 1 ]]
BUILD_AUX_COMMIT=$1

# Initialize for split ###############################################

git commit --allow-empty -m "git-subtree init (for split)

This retroactively initializes git-subtree, since build-aux.git was
created by more sophisticated means than \`git subtree split\`.

These magic strings prevent \`git subtree split\` from crawling the
wrong side of the initial merge commit.

git-subtree-dir: build-aux
git-subtree-split: ${BUILD_AUX_COMMIT}"

# Initialize for merge ###############################################

git ls-files -z|grep -z -v ^build-aux/|xargs -r0 git rm -f --
git mv $(git ls-files build-aux) .
rmdir build-aux

git commit -m "git-subtree init (for merge)

This retroactively initializes git-subtree, since build-aux.git was
created by more sophisticated means than \`git subtree split\`.

These magic strings, in conjuction with the following merge commit,
identify for \`git subtree merge\` (and thus \`git subtree pull\`),
which commit to use as the merge-base.

git-subtree-dir: build-aux
git-subtree-split: ${BUILD_AUX_COMMIT}"

# Sanity check
git fetch git@github.com:datawire/build-aux
if ! git diff --quiet "$BUILD_AUX_COMMIT" HEAD; then
	echo "The current state of things does not agree with the specified commit $BUILD_AUX_COMMIT" >&2
	false
fi

subtree="$(git rev-parse HEAD)"
git reset --hard HEAD^
git merge --strategy=ours --no-ff "$subtree" -m "Merge commit '${subtree}' as build-aux

This retroactively initializes git-subtree, since build-aux.git was
created by more sophisticated means than \`git subtree split\`.

This merge, in conjunction with the magic strings in preceding commit,
identify for \`git subtree merge\` (and thus \`git subtree pull\`),
which commit to use as the merge-base."

# Reverse the order of the parents--it affects how `git subtree merge`
# finds the merge-base.
head="$(git rev-parse HEAD)"
git replace --graft "$head" $(git show --no-patch --format='%P' "$head" | awk '{print $2, $1}')
git filter-branch -f --env-filter : master^..master
git replace -d "$head"
git for-each-ref --format='%(refname)' refs/original|xargs -n1 -r git update-ref -d
