#!/bin/bash
set -e

if ! git diff-index --quiet HEAD; then
    set +x
    echo "There are uncommitted changes:"
    git status --short
    echo "Doing nothing to avoid losing your work."
    exit 1
fi

main_branch=${1:-"upstream/main"}

if [ ! "$1" ]; then
    echo "Using default main branch '$main_branch'"
    if ! git diff --quiet "$main_branch" main; then
        set +x
        echo "Branch '$main_branch' appears to differ from 'main'; please specify one!"
        exit 1
    fi
else
    echo "Specified main branch as '$main_branch'"
fi

if git diff --quiet "$main_branch" HEAD; then
    set +x
    echo "No changes! Nothing to do!"
    exit 1
fi

# By default run 'make check' on each commit, if CHECK is not set
command_per_commit=${CHECK:-"make check"}

echo "Checking commits..."
git rebase $(git merge-base "$main_branch" @) --exec "git --no-pager log -1 && $command_per_commit"
