#!/bin/bash
set -exuo pipefail

if test x$CI_DEFAULT_BRANCH = x
then
    : Environment variable CI_DEFAULT_BRANCH not set.
    exit 1
fi
: HEAD is $(git rev-parse HEAD).
MAIN=refs/remotes/origin/$CI_DEFAULT_BRANCH
: Default branch is $CI_DEFAULT_BRANCH, $(git rev-parse $MAIN).
if git merge-base --is-ancestor $MAIN HEAD
then
    : $CI_DEFAULT_BRANCH can be fast-forwarded.
    :
    : Commits since $CI_DEFAULT_BRANCH:
    git log --format=oneline $MAIN..HEAD
    :
    : Authenticating commits:
    sq-git log --keep-going --trust-root `git rev-parse $MAIN`
else
    FORK=`git merge-base $MAIN HEAD || true`
    if test x$FORK = x
    then
        : Failing.  HEAD does not appear to have a common fork point
        : with $MAIN.
        :
        : If HEAD and $MAIN have a common fork point, then you
        : probably did a shallow clone.
        :
        git rev-parse --is-shallow-repository
        :
        : If so, go to:
        :
        :   Project / Settings / CI/CD / General pipelines / Git strategy
        :
        : And make sure "git shallow clone" is set to "0".  This causes
        : gitlab to fetch all of the history.
        :
        : Alternatively, you can use the GIT_DEPTH variable to set this on
        : a per-job basis.
        exit 1
    else
        : MR needs to be merged or rebased.  Fork point is $FORK.
        :
        : Authenticating commits:
        git log --format=oneline $FORK..HEAD
        :
        : Authenticating commits, using fork point $FORK as trust root:
        sq-git log --keep-going --trust-root $FORK

        : Failing.  Cannot fast-forward $MAIN.
        exit 1
    fi
fi
