#!/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
}

base_commit() {
    tip_commit=${1:-@}
    upstream=${2:-$(upstream_ref)}
    git merge-base "$tip_commit" "$upstream"
}

# usage: files_changed [TIP [UPSTREAM]]
#
# Lists files that have changed in TIP (default: current worktree)
# relative to UPSTREAM (default: upstream/main or origin/main).
#
# Excludes files that no longer exist in TIP.
files_changed() {
    base=$(base_commit "$@")
    git diff --name-only --diff-filter=d "$base" $1
}

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