@echo off
setlocal EnableExtensions
title Add mtcode to PATH

REM ============================================================================
REM add_mtcode_to_path.bat
REM   Adds THIS folder (where mtcode.exe lives) to the current user's PATH so
REM   you can type `mtcode` from any folder / terminal.
REM
REM   - User PATH only. No admin rights, no UAC prompt.
REM   - Safe to run more than once (it won't add a duplicate).
REM   - Does NOT launch mtcode. You still start the app with mtcode.exe.
REM
REM   Just double-click this file, then open a NEW terminal.
REM ============================================================================

REM Folder this .bat lives in (strip the trailing backslash from %~dp0)
set "MTCODE_DIR=%~dp0"
if "%MTCODE_DIR:~-1%"=="\" set "MTCODE_DIR=%MTCODE_DIR:~0,-1%"

echo.
echo   This will add the following folder to your PATH:
echo       %MTCODE_DIR%
echo.

REM Sanity check: make sure mtcode.exe is actually next to this script, so we
REM don't add the wrong folder if the .bat gets moved somewhere on its own.
if not exist "%MTCODE_DIR%\mtcode.exe" (
    echo   ERROR: mtcode.exe was not found next to this script.
    echo          Keep add_mtcode_to_path.bat in the same folder as mtcode.exe
    echo          and run it again.
    goto :fail
)

REM Do the work in PowerShell:
REM   - read the RAW user PATH from the registry (keeps existing entries intact)
REM   - skip if this folder is already present (case/trailing-slash insensitive)
REM   - otherwise append and save via .NET, which also notifies open apps so new
REM     terminals pick it up without a reboot.
REM Exit codes: 0 = added, 3 = already present, 1 = error.
powershell -NoProfile -ExecutionPolicy Bypass -Command "$dir=$env:MTCODE_DIR; try { $k=[Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment',$true); if(-not $k){$k=[Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')}; $raw=[string]$k.GetValue('Path','',[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames); $parts=@($raw -split ';' | Where-Object {$_ -ne ''}); if($parts | Where-Object {$_.TrimEnd('\') -ieq $dir.TrimEnd('\')}){ exit 3 }; $new=(@($parts)+$dir) -join ';'; [Environment]::SetEnvironmentVariable('Path',$new,'User'); exit 0 } catch { Write-Host $_.Exception.Message; exit 1 }"

if %errorlevel% equ 3 goto :already
if %errorlevel% equ 0 goto :added
goto :fail

:added
echo.
echo   DONE. mtcode was added to your PATH.
echo.
echo   Open a NEW terminal (close any that are already open), then you can run:
echo       mtcode
echo   from any folder.
echo.
goto :end

:already
echo.
echo   Nothing to do - this folder is already on your PATH.
echo   Open a new terminal and run:  mtcode
echo.
goto :end

:fail
echo.
echo   Could not update PATH.
echo.
echo   Press any key to close this window.
pause >nul
endlocal
exit /b 1

:end
echo   Press any key to close this window.
pause >nul
endlocal
exit /b 0
