#!/bin/zsh -feu


usage()
{
    setopt POSIX_ARGZERO
    cat <<EOF
usage: ${0##*/} [+-h] [--] {worktree} [{FROM} | {ref}]

worktree ... is the directory

Description:
===========
Syncs 2 git worktrees, by git commands:
Either {ref} is given or we STASH & sync to HEAD of {FROM}.

EOF
}

# todo: git worktree list --porcelain
# convert the NAME into directory.

while getopts :h OPT; do
    case $OPT in
        h|+h)
            usage
            exit 0
            ;;
        *)
            usage >&2
            exit 2
    esac
done
shift OPTIND-1
OPTIND=1

if [ $# -lt 2 ]; then
    usage >&2
    exit 1;
fi

readonly TARGET=$1

if [[ ! -d $2 ]]; then
    sha=$(git rev-parse $2)
else
    #by default:
    sha=$(
        cd $2
        # get the id:
        # sha=$(git rev-parse HEAD)
        sha=$(git stash create)

        if [ -z "$sha" ];
        then
            cecho yellow "no stash created" >&2
            sha=$(git rev-parse HEAD)
        fi

        echo $sha
       )
fi

# there is a race w/ "git gc" which might drop the $sha commit.
cd $TARGET;
sha_from=$(git rev-parse HEAD)
git reset --hard $sha

git diff --name-status $sha_from
