#!/bin/zsh -eu

# fixme: the remote should be remote/branch and branch only the local one, unless implicitly the current one.
source /usr/share/mmc-shell/git-functions.sh
source /usr/share/mmc-shell/mmc-functions.sh
colors

usage()
{
    setopt POSIX_ARGZERO
    cat <<EOF
usage: ${0##*/} [+-h] [-q] [--] [remote] [branch]

remote is by default the "favourite" one.
-q  don't dump the commits

EOF
}


verbose=y
while getopts :hqv OPT; do
    case $OPT in
        h|+h)
            usage
            exit 0
            ;;
        q)
            verbose="n"
            ;;
        v)
            set -x
            verbose=yy
            ;;
        *)
            usage >&2
            exit 2
    esac
done
shift OPTIND-1
OPTIND=1

# the remote:
if [ $# -gt 1 ]; then
    GIT_REMOTE_NAME=$1
    shift
else
    set_remote_name
fi

# the branch
if [ $# -gt 1 ]; then
    branch=$1
    shift
else
    # fixme: this can be empty!
    branch=$(git_current_branch_name)
    if [[ $? != 0 ]]; then
        die "not on a branch -> cannot compare"
    fi
fi

# so the remote branch:
REMOTE=remotes/$GIT_REMOTE_NAME/$branch


# I need the exit status, and it won't be zero:
# could compare with FETCH_HEAD

# Zsh claims that in && expressions all but the last don't make -e trigger the exit.
compare_commits $branch $REMOTE && :
cmp=$?

args=(--max-count 15)
case $cmp in
    0)
        cecho bold "same"
        ;;
    1)
        echo "HEAD $fg_bold[green]$bg[red]ahead$reset_color of $REMOTE"

        if [[ $verbose = yy ]]; then
            git diff --shortstat  $REMOTE
            git log $args --oneline $REMOTE..HEAD --
        fi
        ;;
    2)
        cecho hiyellow "local is behind"
        if [[ $verbose != n ]]; then
            git log $args --oneline HEAD..$REMOTE --
        fi
        ;;
    4)
        echo "error in comparing $branch & FETCH_HEAD"
        ;;
    3)
        cecho red "diverged"
        ;;
    *)
        echo "error while comparing: $cmp"
esac

exit 0
