#!/usr/bin/env bash
#
# Seek the working tree to a given commit.
# Copyright (c) Petr Baudis, 2005
#
# This 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 intiutiveness, 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-fork.
#
# Takes the target commit ID.

. 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
	branch=$(basename $(readlink .git/HEAD)) || die "HEAD is not on branch"
fi

curcommit=$(commit-id)

rm .git/HEAD
if [ ! "$dstcommit" ] || [ "$dstcommit" = "$branch" ]; then
	ln -s "refs/heads/$branch" .git/HEAD
	rm .git/blocked
	dstcommit=$(commit-id)
else
	echo $(commit-id "$dstcommit") >.git/HEAD
	[ -s .git/blocked ] || echo "seeked from $branch" >.git/blocked
fi

if [ "$curcommit" != "$dstcommit" ]; then
	read-tree -m $(tree-id)
	cg-diff -r $curcommit:$dstcommit | cg-patch
	update-cache --refresh
fi

echo "On commit $dstcommit"
