#!/usr/bin/env bash
#
# Seek the working tree to a given commit.
# Copyright (c) Petr Baudis, 2005
#
# Takes the target commit ID to seek to as an argument.
# Seeking will bring the working tree from its current 'HEAD' to a given
# commit. Note that it changes just the 'HEAD' of the working tree, not
# the branch it is corresponding to. It will return to the 'HEAD' of
# the appropriate branch if passed no arguments.
#
# Therefore, for a quick excurse to the past of the 'master' branch:
#
#	$ cg-seek git-pasky-0.1
#	$ cg-diff this master	# will do the correct thing
#	$ cg-seek		# will restore what we had before
#
# For intuitiveness, specifying the branch name (`cg-seek master`) will do
# the right thing too. If you want to migrate your working tree to another
# branch, use `cg-clone`.

USAGE="cg-seek [COMMIT_ID]"

. ${COGITO_LIB}cg-Xlib

dstcommit=$1


[ -s $_git/blocked ] && grep -vq '^seeked from ' $_git/blocked && die "action blocked: $(cat $_git/blocked)"
if [ -s $_git/blocked ]; then
	branch=$(grep '^seeked from ' $_git/blocked | sed 's/^seeked from //')
else
	tmp=$(readlink $_git/HEAD)
	[ "$tmp" ] || die "HEAD is not on branch"
	branch=$(basename "$tmp")
fi

curcommit=$(commit-id)

if [ "$dstcommit" ] && [ "$dstcommit" != "$branch" ]; then
	seek_mode=away
else
	seek_mode=back
	dstcommit=$(commit-id "$branch")
fi

dstcommit=$(commit-id "$dstcommit")
if [ "$curcommit" != "$dstcommit" ]; then
	tree_timewarp --no-head-update "along" "please rollback" $curcommit $dstcommit
fi

if [ "$seek_mode" = "away" ]; then
	rm $_git/HEAD
	echo "$dstcommit" >$_git/HEAD
	[ -s $_git/blocked ] || echo "seeked from $branch" >$_git/blocked
else
	rm $_git/HEAD
	ln -s "refs/heads/$branch" $_git/HEAD
	rm -f $_git/blocked
fi

echo "On commit $dstcommit"
