#!/usr/bin/env bash
# Copyright (c) 2026 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.

# clang-format 检查脚本,用于本地开发与 CI
# 用法:
#   ./scripts/check_format.sh          # 仅检查,不修改文件
#   ./scripts/check_format.sh --fix    # 自动格式化并修改文件

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

FIX_MODE=false
if [[ "${1:-}" == "--fix" ]]; then
    FIX_MODE=true
fi

CLANG_FORMAT="clang-format"
if ! command -v "${CLANG_FORMAT}" &>/dev/null; then
    echo "错误: 未找到 clang-format,请安装后重试"
    echo "  Ubuntu/Debian: sudo apt install clang-format"
    echo "  CentOS/RHEL:   sudo yum install clang-tools-extra"
    exit 1
fi

VERSION=$("${CLANG_FORMAT}" --version)
echo "使用 ${VERSION}"

CONFIG_FILE="${PROJECT_ROOT}/.clang-format"
if [[ ! -f "${CONFIG_FILE}" ]]; then
    echo "错误: 未找到 .clang-format 配置文件 (${CONFIG_FILE})"
    exit 1
fi

# 收集需要检查的 C/C++ 源文件(排除第三方和生成目录)
FILES=$(git -C "${PROJECT_ROOT}" ls-files -- '*.cpp' '*.hpp' '*.h' '*.c' '*.cc' '*.cxx' \
    | grep -v -E '(third_party/|builddir/|subprojects/|\.vscode/)' \
    || true)

if [[ -z "${FILES}" ]]; then
    echo "没有需要检查的 C/C++ 文件"
    exit 0
fi

if ${FIX_MODE}; then
    echo "正在格式化文件..."
    echo "${FILES}" | xargs "${CLANG_FORMAT}" -i
    echo "格式化完成"
else
    echo "正在检查格式..."
    DIFF_OUTPUT=$(echo "${FILES}" | xargs "${CLANG_FORMAT}" --dry-run --Werror 2>&1 || true)

    if [[ -n "${DIFF_OUTPUT}" ]]; then
        echo "以下文件格式不符合 .clang-format 规则:"
        echo "${DIFF_OUTPUT}"
        echo ""
        echo "请运行 ./scripts/check_format.sh --fix 自动修复,或手动格式化"
        exit 1
    else
        echo "所有文件格式检查通过"
    fi
fi