@echo off
:: setup_driver.bat
:: Run as Administrator

echo ============================================
echo   Kernel Driver Setup Script
echo ============================================
echo.

:: Check admin
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo [ERROR] Must run as Administrator.
    echo Right-click this file and select "Run as administrator"
    pause
    exit /b 1
)

:: Check Secure Boot via registry (most reliable method)
echo Checking Secure Boot status...
reg query "HKLM\SYSTEM\CurrentControlSet\Control\SecureBoot\State" /v UEFISecureBootEnabled >nul 2>&1
if %errorLevel% neq 0 (
    echo [OK] Secure Boot not present (Legacy BIOS or disabled^)
    goto :check_testsign
)

for /f "tokens=3" %%a in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\SecureBoot\State" /v UEFISecureBootEnabled 2^>nul') do (
    if "%%a"=="0x1" (
        echo.
        echo [ERROR] Secure Boot is ENABLED.
        echo.
        echo You must disable it in your BIOS/UEFI:
        echo   1. Restart your PC
        echo   2. Press DEL, F2, or F12 during boot to enter BIOS
        echo   3. Navigate to Security ^> Secure Boot ^> Disable
        echo   4. Save and Exit
        echo   5. Run this script again
        echo.
        pause
        exit /b 1
    )
)
echo [OK] Secure Boot is disabled.

:check_testsign
:: Check if test signing is already enabled
echo Checking test signing status...
bcdedit /enum {current} 2>nul | findstr /i "testsigning.*Yes" >nul 2>&1
if %errorLevel% equ 0 (
    echo [OK] Test signing is already enabled.
    goto :check_file
)

:: Not enabled, enable it now
echo [*] Test signing is not enabled. Enabling...
bcdedit /set testsigning on >nul 2>&1
:: Check the ACTUAL result by querying again
bcdedit /enum {current} 2>nul | findstr /i "testsigning.*Yes" >nul 2>&1
if %errorLevel% neq 0 (
    echo [ERROR] Failed to enable test signing.
    echo         Make sure Secure Boot is disabled and you are running as admin.
    pause
    exit /b 1
)

echo [OK] Test signing enabled successfully.
echo.
echo [!!] YOU MUST REBOOT for this to take effect.
echo.
set /p reboot="Reboot now? (y/n): "
if /i "%reboot%"=="y" (
    shutdown /r /t 3 /c "Rebooting to enable test signing"
)
exit /b 0

:check_file
:: Check driver file
if not exist "%~dp0MemReader.sys" (
    echo.
    echo [ERROR] MemReader.sys not found in %~dp0
    echo Place the driver file next to this script.
    pause
    exit /b 1
)

echo [OK] Driver file found.
echo.
echo ============================================
echo   Setup complete! You can now run the app.
echo ============================================
pause