#!/usr/bin/env bash

# Usage (from repo root):
# "./utl/clang-format fix" formats your code.
# "./utl/clang-format check" exits with non-zero if your code isn't formatted correctly.
# Intended to be used with clang-format 7.0.1.
# Set environment variable GH_WORKFLOW_LOGGING to output logging that Azure pipelines will interpret as a warning.
# Set environment variable WARNING_AS_ERROR to make the script exit with a non-zero code if issues are found.

for VW_FILE in $(find vowpalwabbit python -type f -name '*.cc' -o -name '*.h'); do

    if [ "$1" = check ]; then
        diff $VW_FILE <(clang-format $VW_FILE);
        if [ $? -ne 0 ]; then
            ISSUE_FOUND="true"
            if [[ -v GH_WORKFLOW_LOGGING ]]; then
                echo "::warning file=$VW_FILE:: Formatting issues found in $VW_FILE"
            fi
        fi
    fi

    if [ "$1" = fix ]; then
        clang-format -i $VW_FILE;
    fi

done

if [[ -v ISSUE_FOUND ]]; then
    echo -e "\nFormatting issues found:\n\tRun \"./utl/clang-format fix\""
    if [[ -v WARNING_AS_ERROR ]]; then
        echo -e "\nTreating as failure because WARNING_AS_ERROR was set"
        exit 1
    fi
fi
