#!/usr/bin/env bash
#
# Get ID of commit associated with given id or HEAD.
# Copyright (c) Petr Baudis, 2005
#
# Takes the appropriate ID, defaults to HEAD.

SHA1="[A-Za-z0-9]{40}"
SHA1ONLY="^$SHA1$"

id=$1
if [ ! "$id" ] || [ "$id" = "this" ] || [ "$id" = "HEAD" ]; then
	id=$(cat .git/HEAD)
fi

if (echo $id | egrep -vq "$SHA1ONLY") && [ -r ".git/refs/tags/$id" ]; then
	id=$(cat ".git/refs/tags/$id")
fi

if (echo $id | egrep -vq "$SHA1ONLY") && [ -r ".git/refs/heads/$id" ]; then
	id=$(cat ".git/refs/heads/$id")
fi

idpref=$(echo "$id" | cut -c -2)
idpost=$(echo "$id" | cut -c 3-)
if [ $(find ".git/objects/$idpref" -name "$idpost*" 2>/dev/null | wc -l) -eq 1 ]; then
	id=$idpref$(basename $(echo .git/objects/$idpref/$idpost*))
fi

if echo $id | egrep -vq "$SHA1ONLY"; then
	echo "Invalid id: $id" >&2
	exit 1
fi

if [ "$(cat-file -t "$id")" != "commit" ]; then
	echo "Invalid id: $id" >&2
	exit 1
fi

echo $id
