#!/bin/sh
set -e

usage () {
    cat <<'EOF'
usage: git sha [-sq] [<object>]

Options:
-s    Output short SHAs
-q    Be quiet (only return exit code 0 when object exists)
-h    Show this help

<object> defaults to HEAD
EOF
}

short=0
quiet=0
while getopts sqh flag; do
    case "$flag" in
        s) short=1;;
        q) quiet=1;;
        h) usage; exit 0;;
    esac
done
shift $(($OPTIND - 1))

if [ $# -eq 1 ]; then
    object=$1
else
    object="HEAD"
fi

opts=""
if [ $short -eq 1 ]; then
    opts="--short"
fi

set +e
output=$(git rev-parse $opts "$object" 2>/dev/null)
status=$?
set -e
if [ $status -ne 0 ]; then
    echo "Invalid object: '$object'" >&2
    exit 1
else
    if [ $quiet -eq 0 ]; then
        echo "$output"
    fi
    exit 0
fi
