#! /bin/zsh -feu

. /usr/share/mmc-shell/mmc-functions.sh
check_getopt


## Keep the local git repo up-to-date (fetch from remotes) & report situation.
## i.e. compare (local branch) head with a remote head.

## `Defaults'
branch=HEAD
verbose=no
remotes=()
fast_forward=no

usage()
{
    setopt POSIX_ARGZERO
    cat <<EOF
usage: ${0##*/} [+-f] [-r <remote>| -a]  [--] ARGS...
-r | --remote [remote]   ....
-a | --all
-f | --ff fast-forward to the fetched remote-branch
-v | --verbose
EOF
}


# how can I have optional argument to ... ?
cmd_options=$(getopt --name ${0##*/} --shell bash \
        --longoptions all,ff:,remote:,verbose --options afhr:v \
        -- "$@" ) || { usage && exit 1 }

eval set -- "$cmd_options"

while (( $# > 0 )); do
    case $1 in
        -h | --help)
            usage
            exit 0
            ;;
        --all | -a)
            remote="--all"
            ;;
        --ff | -f)
            fast_forward=y
            ;;
        --remote | -r)
            shift
            # better +=
            remotes+=($1)
            ;;
        -v | --verbose)
            verbose=y
            set -x
            ;;
        --)
             shift
             break
             ;;
        *)
            echo $1>&2
            usage
            exit 2
    esac
    shift
done

# Determine the remotes:
if [ $# -gt 0 ]; then
    remotes+=($@)
fi

# do the fetch
# todo: empty-array test?
if [ -z "${remotes}" ];
then
    if [ $verbose = y ]; then echo "will fetch from all remotes";fi

    git fetch "--all" --quiet
    git status --short
else
    if [ $verbose = y ]; then echo "will fetch from: $remotes";fi
    foreach remote ($remotes) {
        git fetch --tags ${remote}
        # --quiet
    }
fi

# report the change:
foreach remote ($remotes) {
    git-compare-remote $remote master
}

if [[ $fast_forward = y && ${#remotes} = 1 ]]; then
    # the same-named branch on the remote:
    git-ff $remotes[1]
fi
