#!/bin/sh
#
# Copyright (C) 2013-2015, 2017  Etersoft
# Copyright (C) 2013-2015, 2017  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

PROGDIR=$(dirname $0)
[ "$PROGDIR" = "." ] && PROGDIR=$(pwd)

. $PROGDIR/giter-common-functions
. $PROGDIR/giter-git-functions


# Do git rebase -i

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
	echo "grebase - do interactive rebase for last N commits"
	echo "Use: grebase [-f] [N|ID]"
	echo "   N  - number of the commit (will ask if empty)"
	echo "  ID  - commit ID (for long log list case)"
	echo "   -f -  force rebase ever for published commits"
	exit 0
fi

EXTEXT=
NOTREMOTES="$(get_current_branch) --not --remotes"
if [ "$1" = "-f" ] ; then
	shift
	NOTREMOTES=
else
	EXTEXT=" (only non published commits, use -f for full list)"
fi

set_merge_ff

commit=''
# if $1 is a commit ID
if [ "$(echo "$1" | wc -c)" -ge 5 ] ; then
	commit="$1"
	docmd git rebase -i "$commit^"
	exit
fi

NN="$1"

tmpfile=$(mktemp) || fatal

if [ -z "$NN" ] ; then
	git log $NOTREMOTES --pretty=format:"%h %s, %cd" | head -n 20 > $tmpfile
	[ -s "$tmpfile" ] || fatal "No unpublished commits. You can use -f option if you know what you doing."
	echo "Will do commit rebase. Last commit list$EXTEXT:"
	cat -n $tmpfile
	echo
	echo "Input line number or Ctrl-C to exit:"
	read NN other
else
	git log --pretty=format:"%h %s, %cd" | head -n 100 > $tmpfile
fi

# force numeric
NN=$(($(echo "$NN" | sed -e "s|[^0-9]*||g")))
[ "$NN" = "0" ] && fatal "Incorrect number format"

commit=$(cat $tmpfile | sed -n "${NN}p" | sed -e "s| .*||g")
[ -n "$commit" ] || fatal "Logic error can't find commit $NN in $(cat $tmpfile)"
rm -f $tmpfile

docmd git rebase -i "$commit^"
