@echo off
setlocal enabledelayedexpansion

echo ========================================
echo    Samovaritch Libraries Installer
echo ========================================

:: Автоматическое определение папки Arduino
set "ARDUINO_PATH=%USERPROFILE%\Documents\Arduino"
if not exist "%ARDUINO_PATH%" (
    echo ERROR: Arduino folder not found at: %ARDUINO_PATH%
    echo Please make sure Arduino IDE is installed and Documents folder exists.
    pause
    exit /b 1
)

set "ARDUINO_LIB=%ARDUINO_PATH%\libraries"
set "SCRIPT_PATH=%~dp0"
set "PROJECT_LIB=%SCRIPT_PATH%libraries"

echo Arduino Libraries: %ARDUINO_LIB%
echo Project Libraries: %PROJECT_LIB%
echo.

:: Проверка существования папки libraries в проекте
if not exist "%PROJECT_LIB%" (
    echo ERROR: Project libraries folder not found!
    echo Please make sure this script is in the project folder.
    pause
    exit /b 1
)

:: Поиск свободного имени для бэкапа
set "BACKUP_COUNT=0"
:find_backup
if exist "%ARDUINO_LIB%_old_!BACKUP_COUNT!" (
    set /a BACKUP_COUNT+=1
    goto find_backup
)

:: Переименование существующей папки libraries (если существует)
if exist "%ARDUINO_LIB%" (
    echo Renaming existing libraries folder...
    ren "%ARDUINO_LIB%" "libraries_old_!BACKUP_COUNT!"
    if !errorlevel! equ 0 (
        echo Backup created: libraries_old_!BACKUP_COUNT!
    ) else (
        echo ERROR: Failed to rename libraries folder!
        pause
        exit /b 1
    )
    echo.
)

:: Создание новой чистой папки libraries
echo Creating new libraries folder...
mkdir "%ARDUINO_LIB%"
if !errorlevel! neq 0 (
    echo ERROR: Failed to create libraries folder!
    pause
    exit /b 1
)

:: Копирование библиотек из проекта
echo Installing project libraries...
set "COPIED_COUNT=0"

for /d %%i in ("%PROJECT_LIB%\*") do (
    set "libname=%%~nxi"
    set "source_path=%%i"
    set "dest_path=%ARDUINO_LIB%\!libname!"
    
    echo [INSTALL] !libname!
    xcopy "!source_path!" "!dest_path!\" /E /I /Y >nul
    if !errorlevel! equ 0 (
        set /a COPIED_COUNT+=1
    ) else (
        echo [ERROR] Failed to copy !libname!
    )
)

echo.
echo ========================================
echo    Installation Complete!
echo ========================================
echo Libraries installed: !COPIED_COUNT!
if defined BACKUP_COUNT (
    echo Original libraries backed up as: libraries_old_!BACKUP_COUNT!
)
echo.
echo You can now compile the project in Arduino IDE!
echo.
pause