#!/bin/bash
# Copyright, the authors of the Linux man-pages project
# SPDX-License-Identifier: GPL-3.0-or-later

set -Eeufo pipefail;
shopt -s lastpipe;

git rev-parse --git-path bisect-rebase | read -r dir;
xargs git checkout --detach <"$dir/onto" 2>/dev/null;
if git-bisect-rebase--callback; then
	xargs git checkout <"$dir/head-name" >/dev/null 2>/dev/null;
	rm -rf "$dir";
	exit 0;
fi;

readarray -t git_bisect_options <"$dir/git-bisect-options";
git bisect start "${git_bisect_options[@]}" >/dev/null;
xargs git bisect bad <"$dir/onto" >/dev/null;
cat "$dir/head-name" "$dir/onto" | xargs git merge-base | xargs git bisect good;
git bisect run git-bisect-rebase--callback;
git rev-parse --verify bisect/bad >"$dir/bisect-bad";
git bisect reset >/dev/null 2>/dev/null;

xargs git checkout <"$dir/head-name" >/dev/null 2>/dev/null;
readarray -t git_rebase_options <"$dir/git-rebase-options";
xargs git rebase "${git_rebase_options[@]}" <"$dir/bisect-bad";
if test -e "$dir/post-exec"; then
	cat <(printf '%s' 'Executing (post-rebase): ') "$dir/post-exec";
	bash "$dir/post-exec";
fi;

exec git-bisect-rebase--continue;
