#!/usr/bin/zsh -feu

# output:
# --------------
# dir
# sha [ref] [stash]
#-------------
# the HEAD ref (either sha or symbolic ref).
# Possibly also a stash SHA1 --
# git stash -- "No local changes to save" does nothing then.
# git-reset, unless

# create stash too.
stash=y

# reset/clean the git repo:
reset=y

# git stash -m "pre-repo-sync"
# git stash create
# git stash store -m
usage(){
    print "usage: ${0##*/} [+-s}"
}


while getopts :s OPT; do
    case $OPT in
	s|+s)
	    # dont-stash
	    stash=n
	    reset=n
	    ;;
	*)
	    usage
	    exit 2
    esac
done
shift OPTIND-1
OPTIND=1

# ====
# fixme:
symbolic=$(cat .git/HEAD)
sha=$(git rev-parse HEAD)
# fixme: not pwd, just RELATIVE path!
: ${REPO_PATH=`pwd`}
echo -n "$REPO_PATH\t$sha"

set +e
#=$(expr match "$symbolic"  '^(rev: .+)$')
matched=$(expr match "$symbolic"  '^ref: .*$')
#&> /dev/null
# res=$?
if [ $matched -gt 1 ]; then
    echo -n  "\t$symbolic"; #${a#ref: };
else
    :
fi
set -e



if test $stash = y;
then
    msg="pre repo-sync $(date +%m-%d)"
    # fixme: what if this fails?
    sha=$(git stash create "$msg")

    if [ -n "$sha" ];
    then
	git stash store -m "$msg" $sha
    fi
    echo -en "\t" $sha
fi

# newline:
echo

test "$reset" = y && git reset --hard > /dev/null

exit 0
