#!/usr/bin/env bash
###
#
#  @file check_ci.sh
#  @copyright 2023-2023 Bordeaux INP, CNRS (LaBRI UMR 5800), Inria,
#                       Univ. Bordeaux. All rights reserved.
#
#  @version 6.3.2
#  @author Mathieu Faverge
#  @author Florent Pruvost
#  @date 2023-12-07
#
###
success=1

check_rebase()
{
    hash_master=$(git show-ref -s origin/master)
    hash_common=$(git merge-base origin/master ${CI_COMMIT_SHA})
    if [ "${hash_master}" = "${hash_common}" ]
    then
        echo "check_rebase: OK"
        return 0
    else
        echo "check_rebase: Rebase is required"
        success=0
        return 1
    fi
}

check_draft()
{
    if [ "${CI_PIPELINE_SOURCE}" = "merge_request_event" ]
    then
        draft=$( echo ${CI_MERGE_REQUEST_TITLE} | sed "s/^Draft.*$/Draft/" )
        wip=$( echo ${CI_MERGE_REQUEST_TITLE} | sed "s/^WIP.*$/WIP/" )

        if [ "$draft" = "Draft" ]
        then
            echo "check_draft: Merge request is in draft mode"
            success=0
            return 1
        fi

        if [ "$wip" = "WIP" ]
        then
            echo "check_draft: Merge request is in WIP"
            success=0
            return 1
        fi

        # if [ "${CI_MERGE_REQUEST_APPROVED}" != "true" ]
        # then
        #     echo "check_approval: Merge request not yet approved"
        #     success=0
        #     return 1
        # fi

        echo "check_draft: Merge request is ok"
    fi

    return 0
}

check_header()
{
    echo " Checking file headers: "
    TOOLSDIR=$(dirname $0)/../tools

    $TOOLSDIR/check_header.sh
    rc=$?
    if [ $rc -eq 0 ]
    then
        echo "Check header: SUCCESS"
    else
        echo "Check header: FAILED"
        success=0
    fi
}

check_clang-format()
{
    local clang_success=0
    if [ "${CI_PIPELINE_SOURCE}" = "merge_request_event" ]
    then
        clang-format --version

        git diff -U0 --no-color origin/master | clang-format-diff -p1 > format-diff.log
        exit_status=$?
        [ ${exit_status} == 0 ] || exit ${exit_status}
        format_diff="$(<format-diff.log)"
        if [ -n "${format_diff}" ]; then
            cat format-diff.log
            clang_success=1
        fi
    fi

    if [ $clang_success -eq 0 ]
    then
        echo "check_clang-format: OK"
        return 0
    else
        echo "check_clang-format: FAILED (Please run clang commands listed above)"
        success=0
        return 1
    fi
}

usage()
{
    echo "Usage: $0 [rebase|draft|header|clang-format]"
    exit 1
}

if [ $# -lt 1 ]
then
    usage
fi

echo ""
echo "----------------------------------------------------"
case $1 in
    rebase)
	check_rebase
	;;
    draft)
	check_draft
	;;
    header)
	check_header
	;;
    clang-format)
	check_clang-format
	;;
    *)
        usage
	;;
esac

if [ $success -eq 0 ]
then
    exit 1
fi
