#!/usr/bin/env bash
# git-link-history - link history of two Git branches

set -e

if (( $# != 2 )); then
	echo "Usage: git link-history <current-branch> <history-branch>"
	echo ""
	echo "Prepend <history> as a parent of the initial commit of <current>."
	exit 2
fi

newtail=$(git --no-replace-objects rev-list "$1^{commit}" | tail -1)
oldhead=$(git --no-replace-objects rev-parse --verify "$2^{commit}")

parent=$(git rev-parse --verify "$newtail^" 2>/dev/null || true)

if [[ "$parent" ]]; then
	echo "error: initial commit of $1 already has a fake parent"
	exit 1
else
	git replace --graft "$newtail" "$oldhead"
	git log -n 2 --decorate "$newtail"
fi
