#!/usr/bin/env bash
#
# Undo a commit or a series of commits.
# Copyright (c) Matt Porter, 2005
# Copyright (c) Petr Baudis, 2005
#
# Takes a commit ID which is the earliest commit to be removed from
# the repository. If no parameter is passed, it uncommits the latest
# commit ('HEAD').
#
# OPTIONS
# -------
# -t::
#	This optional parameter makes `cg-admin-uncommit` to roll back
#	the tree as well to the previous commit. Without this option
#	(by default) Cogito keeps the tree in its current state,
#	therefore generating tree with local changes against the target
#	commit, consisting of the changes in the rolled back commits.

USAGE="cg-admin-uncommit [-t] [COMMIT_ID]"

. ${COGITO_LIB}cg-Xlib

[ -s $_git/blocked ] && die "uncommitting blocked: $(cat $_git/blocked)"

rollback_tree=
if [ "$1" = "-t" ]; then
	shift
	rollback_tree=1
fi


base=$(commit-id) || exit 1

commit=$(commit-id "$1") || exit 1
git-rev-list $base | grep -q $commit || \
	die "$commit: not an ancestor of HEAD"

parent=$(parent-id "$commit") || exit 1
[ "$parent" ] || die "cannot rewind behind the initial commit"


echo "Rewinding $base (HEAD) -> $parent" >&2

tree_timewarp "backwards" "$rollback_tree" $base $parent
