#!/bin/bash

# Helper script to get the list of changed files for this build.
# If a PR it lists the changes from the target branch.
# If a 'regular' branch build the changes since the last build.

set -e

function files_list
{
    git diff --name-only --diff-filter ACMRT "$@"
}

if [ "$TRAVIS" = "true" ]
then
    # https://docs.travis-ci.com/user/environment-variables/
    if [ -n $TRAVIS_COMMIT_RANGE ]
    then
        # If this string is populated, it should work.
        # But it mught fail, due to e.g. the shallow clone depth missing the
        # relevant commit, in which case we fail
        files_list $TRAVIS_COMMIT_RANGE || exit 1
    else
        # The only time it isn't populated is on a new PR branch, where THIS will work.
        files_list $TRAVIS_BRANCH
    fi
elif [ -n "$GITHUB_BASE_REF" ]
then
    base="origin/$GITHUB_BASE_REF"
    # We need to fetch enough commits to be able to compute the merge-base
    # between this PR and master
    commits_to_fetch=10
    fetch_limit=10000
    while [ -z "$( git merge-base "$base" HEAD^2 2>/dev/null )" ]
    do
        git fetch -q --deepen=$commits_to_fetch origin "$GITHUB_BASE_REF" HEAD
        (( commits_to_fetch *= 2 ))
        if [ "$commits_to_fetch" -gt "$fetch_limit" ]
        then
            printf '%s\n' "Already fetched over $fetch_limit commits" \
                'Giving up on trying to find merge-base' >&2
            exit 1
        fi
    done
    files_list "$( git merge-base "$base" HEAD^2 )..HEAD^2"
elif [ -n "$GIT_LOCAL_BASE_REF" ]
then
    files_list "$GIT_LOCAL_BASE_REF..HEAD"
else
    echo 'Neither $TRAVIS nor $GITHUB_BASE_REF was defined' >&2
    exit 1
fi
