#!/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;
readonly dir;
git rev-parse --verify HEAD >"$dir/bisect-head";
trap 'xargs git checkout --detach <"$dir/bisect-head" 2>/dev/null;' EXIT;

if test -e "$dir/pre-exec"; then
	cat <(printf '%s' 'Executing (pre-rebase): ') "$dir/pre-exec";
	bash "$dir/pre-exec";
fi;

xargs git checkout <"$dir/head-name" >/dev/null 2>/dev/null;
git rev-parse --verify HEAD >"$dir/good-head";
readarray -t git_rebase_options <"$dir/git-rebase-options";
trap 'git rebase --abort >/dev/null;' ERR;
xargs git rebase --no-stat "${git_rebase_options[@]}" <"$dir/bisect-head";
trap - ERR;

if test -e "$dir/post-exec"; then
	cat <(printf '%s' 'Executing (post-rebase): ') "$dir/post-exec";
	trap 'xargs git reset --hard <"$dir/good-head";' ERR;
	bash "$dir/post-exec";
	trap - ERR;
fi;

{
	git rev-parse --verify --abbrev-ref HEAD;
	git rev-parse --verify HEAD;
} \
| sed '/^HEAD$/d' \
| sed '1!d' \
>"$dir/head-name";
exit 0;
