#!/bin/bash

set -e
set -x

ORIGIN_REPO=$(git config remote.origin.url)
MODULE_DEFAULTS_TEST_UPDATED=$(git log -1 --pretty=%H)

if [ "$BRANCH_TO" != "None" -a "$BRANCH_TO" != "" ]; then
    git config user.email "noreply@ci.centos.org"
    git config user.name "CentOS CI"

    # Save the commit ID of the baseline checkout
    MODULE_DEFAULTS_TEST_BASELINE=$(git log -1 --pretty=%H origin/$BRANCH_TO)
    export MODULE_DEFAULTS_TEST_BASELINE

    # Merge the PR into the current tree
    git remote rm proposed || true
    git gc --auto
    git remote add proposed "$REPO"
    git fetch proposed

    MODULE_DEFAULTS_TEST_UPDATED=$(git log -1 --pretty=%H proposed/$BRANCH)
    export MODULE_DEFAULTS_TEST_UPDATED

    # Test that it merges cleanly
    git branch -D pullrequest || true
    git checkout -b pullrequest $MODULE_DEFAULTS_TEST_BASELINE
    git merge --no-ff "$MODULE_DEFAULTS_TEST_UPDATED" -m "Merge PR"

    echo "Running tests for branch $BRANCH of repo $REPO"
    echo "Last commits:"
    git log $MODULE_DEFAULTS_TEST_BASELINE..$MODULE_DEFAULTS_TEST_UPDATED

    # If this branch is atop the master, use its tests (possibly updated).
    # Otherwise, check out origin/master for the latest tests.
    set +e
    git merge-base --is-ancestor -- origin/master HEAD
    set -e
    if [ $? -ne 0 ]; then
        git checkout origin/master
    fi

    # Run any tests that only apply to PRs
    tests/pr_tests.sh
fi

git reset --hard $MODULE_DEFAULTS_TEST_UPDATED

# If this branch is atop the master, use its tests (possibly updated).
# Otherwise, check out origin/master for the latest tests.
TEMPDIR=
set +e
git merge-base --is-ancestor -- origin/master HEAD
set -e
if [ $? -ne 0 ]; then
    TEMPDIR=$(mktemp -d)
    git clone $ORIGIN_REPO $TEMPDIR
    TEST_DIR=$TEMPDIR/tests
else
    TEST_DIR=$(pwd)/tests
fi


# Run any tests that apply to either PRs or commits
$TEST_DIR/common_tests.sh $(pwd)/tests

if [ x$TEMPDIR != x ]; then
    rm -Rf $TEMPDIR
fi
