#!/bin/bash
# vim: et sts=4 sw=4

set -euo pipefail

# The following approach was shamelessly copied from ci-fairy
# https://gitlab.freedesktop.org/freedesktop/ci-templates/-/blob/master/tools/ci_fairy.py
# CHANGES: Swap CI for CI_MERGE_REQUEST_ID, add CI_COMMIT_BRANCH.
if [[ ${CI_MERGE_REQUEST_ID-} ]]; then
    upstream="${FDO_UPSTREAM_REPO-}"
    if [[ ! "$upstream" ]]; then
        echo "$FDO_UPSTREAM_REPO not set, using local branches to compare"
        upstream="${CI_PROJECT_PATH}"
    fi
    host="${CI_SERVER_HOST}"
    token="${CI_JOB_TOKEN}"
    url="https://gitlab-ci-token:$token@$host/$upstream"

    remote="clang-fairy"
    if ! git remote | grep -qw "$remote"; then
        git remote add "$remote" "$url"
    fi
    git fetch "$remote"

    # There are two types of MRs apparently
    if [[ ${CI_MERGE_REQUEST_TARGET_BRANCH_SHA-} ]]; then
        echo "Using CI_MERGE_REQUEST_SOURCE_BRANCH_SHA"
        commit=$CI_MERGE_REQUEST_SOURCE_BRANCH_SHA
    elif [[ ${CI_MERGE_REQUEST_DIFF_BASE_SHA-} ]]; then
        echo "Using CI_MERGE_REQUEST_DIFF_BASE_SHA"
        commit=$CI_MERGE_REQUEST_DIFF_BASE_SHA
    else
        echo "Looking like a MR, but CI variables are not set."
        echo "Using the default branch \"$CI_DEFAULT_BRANCH\"."
        commit="$remote/$CI_DEFAULT_BRANCH"
    fi
elif [[ ${CI_COMMIT_BRANCH-} ]]; then
    echo "Using CI_COMMIT_BEFORE_SHA"
    commit=$CI_COMMIT_BEFORE_SHA
else
    commit="master"
fi

# End of the shameless copy

# Older versions of clang-format like 6 and 7 print an annoying message.
# "no modified files to format". Newer ones like 12 (earlier?), do not.
formatting_changes=$(git-clang-format --commit "$commit" -q --diff | grep -v "no modified files to format" || true)
[[ "$formatting_changes" ]] || exit 0

echo "ERROR: Formatting issues detected"
echo
echo "Update the codebase as indicated or disable clang-format locally."
echo
echo "Formatting suggestion:"
echo
echo -e "------------\n$formatting_changes\n------------"
echo

exit 1
