@echo off
echo "start..." > result.log
echo "" > failed.txt
setlocal enabledelayedexpansion

:: 获取当前目录
set "current_dir=%cd%"

:: 获取命令行输入参数，如果没有参数则默认为0（即不跳过任何工程）
set skip_count=0
if "%~1" NEQ "" (
    set /a skip_count=%~1
    if %skip_count% lss 0 (
        echo "输入的跳过数量不能为负数，按默认设置执行（不跳过任何工程）"
        set skip_count=0
    )
)

set current_skip=0
:: 遍历一级子目录
for /d %%D in ("%current_dir%\*") do (
    echo Entering directory: %%D
    cd "%%D"
     :: 检查当前子目录是否存在Makefile文件
    if exist Makefile (
          set /a current_skip+=1
        setlocal
        if !current_skip! geq %skip_count% (
            echo !current_skip! Compiling project: %%D
            
            :: 执行make命令，将输出重定向到build.log，同时将错误输出也重定向到标准输出（2>&1）
            make clean
            make > build.log 2>&1
            
            :: 检查make命令的返回值
            if errorlevel 1 (
                type build.log
                echo !current_skip! Build failed: %%D
                endlocal
                goto :end
            )
        ) else (
            echo Skipping project: %%f !current_skip!
            echo Skipping project: %%f >> result.log
            
        )
        endlocal

    ) else (
        
        if exist Project (
            cd "Project"
                if exist Makefile (
                    set /a current_skip+=1
                    setlocal
                    if !current_skip! geq %skip_count% (
                        echo !current_skip! Compiling project: %%D
                        
                        :: 执行make命令，将输出重定向到build.log，同时将错误输出也重定向到标准输出（2>&1）
                        make clean
                        make > build.log 2>&1
                        
                        :: 检查make命令的返回值
                        if errorlevel 1 (
                            type build.log
                            echo !current_skip! Build failed: %%D
                            endlocal
                            goto :end
                        )
                    ) else (
                        echo Skipping project: %%f !current_skip!
                        echo Skipping project: %%f >> result.log
                        
                    )
                    endlocal

                )
            cd ..
        )
        
    )
    
    :: 返回上级目录
    cd ..

)

echo All directories processed successfully.

:end

if %errorlevel% neq 0 (
    echo Build failed. See build.log for details.
    exit /b 1
)
echo Build successful.
exit /b 0