#!/usr/bin/env bash

# Compute what remote name is being used for the upstream repo.
upstream_remote_name() {
    # Out of the names listed by `git remote`, pick one from the
    # list below, in preference order.
    grep -m1 -xFf <(git remote) <<EOF
upstream
origin
EOF
}

upstream_ref() {
    echo refs/remotes/"$(upstream_remote_name)"/main
}

# usage: base_commit [TIP [UPSTREAM]]
#
# The merge-base of TIP (default: current HEAD) with
# UPSTREAM (default: upstream/main or origin/main).
base_commit() {
    tip_commit=${1:-@}
    upstream=${2:-$(upstream_ref)}
    git merge-base "$tip_commit" "$upstream"
}

# usage: files_changed [DIFFARGS..]
#
# Lists files that have changed, excluding files that no longer exist.
#
# Arguments are passed through to `git diff`.
files_changed() {
    git diff --name-only --diff-filter=d "$@"
}

case "$1" in
    upstream-ref) upstream_ref; exit;;
    base) shift; base_commit "$@"; exit;;
    '' | changed-files) shift; files_changed "$@"; exit;;
    *) exit 1;;
esac
