@echo off
setlocal enabledelayedexpansion

rem Switch to batch file directory so .reg discovery and paths work regardless of invocation directory
cd /d "%~dp0"

rem Resolve batch directory, double backslashes for .reg format, strip trailing \\
set "BAT_DIR=%~dp0"
set "BAT_DIR=%BAT_DIR:\=\\%"
set "BAT_DIR=%BAT_DIR:~0,-2%"

set "ANY_IMPORTED=0"

for %%F in (*.reg) do (
    echo ===== Processing: %%F =====
    set "NEED_IMPORT=0"
    for /f "usebackq tokens=* delims=" %%a in ("%%F") do (
        set "_line=%%a"
        if "!_line:~0,1!"=="[" (
            set "_key=!_line:~1,-1!"
            reg query "!_key!" >nul 2>&1
            if errorlevel 1 (
                echo [MISSING] !_key!
                set "NEED_IMPORT=1"
            ) else (
                echo [EXISTS] !_key!
            )
        )
    )
    echo.
    if !NEED_IMPORT! equ 1 (
        set "TEMP_FILE=%TEMP%\odbc_setup_%%~nF.reg"
        if exist "!TEMP_FILE!" del /q "!TEMP_FILE!"
        for /f "usebackq tokens=* delims=" %%a in ("%%F") do (
            set "_line=%%a"
            set "_line=!_line:%%DRIVERPATH%%=%BAT_DIR%!"
            >>"!TEMP_FILE!" echo !_line!
        )
        echo [INFO] Importing %%F ...
        regedit /s "!TEMP_FILE!"
        if errorlevel 1 (
            echo [ERROR] Import failed. Try running as Administrator.
        ) else (
            echo [INFO] Import complete.
            set "ANY_IMPORTED=1"
        )
        del /q "!TEMP_FILE!"
    ) else (
        echo [INFO] All registry keys already exist. Skipping.
    )
    echo.
)

if %ANY_IMPORTED% equ 0 (
    echo [INFO] No .reg files found or all already registered.
)

rem Check and add Dameng ODBC dependencies to system PATH
set "DEP_DIR=%~dp0Dameng\odbc\dependencies"
if exist "%DEP_DIR%" (
    echo ===== Checking PATH for Dameng ODBC dependencies =====
    for /f "tokens=2*" %%a in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path 2^>nul') do set "SYS_PATH=%%b"
    echo !SYS_PATH! | find /i "%DEP_DIR%" >nul 2>&1
    if errorlevel 1 (
        echo [INFO] Adding %DEP_DIR% to system PATH ...
        setx Path "%DEP_DIR%;!SYS_PATH!" /M
        if errorlevel 1 (
            echo [ERROR] Failed to update PATH. Try running as Administrator.
        ) else (
            echo [INFO] PATH updated. Re-login or restart to take effect.
        )
    ) else (
        echo [INFO] Already in PATH.
    )
    echo.
)

endlocal
