#!/usr/bin/env bash
#
# Resets the state of the working tree.
# Copyright (c) Petr Baudis, 2005
#
# Reverts the working tree to a consistent state before any changes to it
# (including merges etc.) were done. This command will rebuild the state
# of the tree according to the commit of .git/refs/heads/master, so if your
# working tree got into basically any inconsistent state, this will cure it.
#
# Basically, this is the opposite of `cg-commit` in some sense.
#
# This command is complementary to `cg-restore`, which only brings
# individual files in sync with their state at the time of the
# last commit.

USAGE="cg-reset"
_git_requires_root=1

. ${COGITO_LIB:-/usr/lib/cogito/}cg-Xlib

if ! [ -s $_git/HEAD ]; then
	rm -f $_git/HEAD
	ln -s refs/heads/$_git_head $_git/HEAD
fi

# Undo seek?
if [ ! "$(readlink $_git/HEAD)" ]; then
	echo "Unseeking: $(cat $_git/HEAD) -> $(cat "$_git/refs/heads/$_git_head")"
	if [ -s "$_git/refs/heads/$_git_head" ]; then
		rm $_git/HEAD
		ln -s "refs/heads/$_git_head" $_git/HEAD
	else
		echo "ERROR: Unknown branch $_git_head! Preserving HEAD." >&2
	fi
fi

rm -f $_git/blocked $_git/merging $_git/merging-sym $_git/merge-base
git-read-tree -m HEAD || git-read-tree HEAD

git-checkout-cache -f -a
git-update-cache --refresh
