@echo off
REM =====================================================================
REM  kcpp / ICPP installer  (Windows x64)
REM
REM     <home>\bin\        kcpp.exe, icpp.exe, klink.exe, klib.exe,
REM                        khex16.exe, kice.exe, isqldll.dll
REM     <home>\lib\        ICPP libraries (stringutil.icpp)
REM     <home>\doc\        the manuals and the builtin list
REM     <home>\examples\   language / html / llm / fpga samples
REM     <home>\tools\      icpplint.py
REM
REM  Usage:  install.bat [target-home-dir] [options]
REM            /nopath    do not touch PATH
REM            /system    register on the SYSTEM PATH (needs admin)
REM                       default is the per-user PATH (no admin needed)
REM =====================================================================
setlocal EnableExtensions EnableDelayedExpansion

set "SRC=%~dp0"
if "%SRC:~-1%"=="\" set "SRC=%SRC:~0,-1%"

set "DEST="
set "PATHMODE=user"
for %%A in (%*) do (
  if /i "%%~A"=="/nopath"  ( set "PATHMODE=none"
  ) else if /i "%%~A"=="/system" ( set "PATHMODE=machine"
  ) else if not defined DEST ( set "DEST=%%~A" )
)

if not defined DEST (
  echo.
  echo  Enter the directory to install kcpp / ICPP into.
  set /p "DEST=  [C:\kcpp]: "
)
if not defined DEST set "DEST=C:\kcpp"

echo.
echo  installing to %DEST%
mkdir "%DEST%\bin" 2>nul
mkdir "%DEST%\lib" 2>nul
mkdir "%DEST%\doc" 2>nul
mkdir "%DEST%\tools" 2>nul

copy /y "%SRC%\windows-x64\bin\*" "%DEST%\bin\" >nul || goto :failed
xcopy /e /i /y /q "%SRC%\doc"      "%DEST%\doc"      >nul || goto :failed
xcopy /e /i /y /q "%SRC%\examples" "%DEST%\examples" >nul || goto :failed
xcopy /e /i /y /q "%SRC%\lib"      "%DEST%\lib"      >nul || goto :failed
xcopy /e /i /y /q "%SRC%\tools"    "%DEST%\tools"    >nul || goto :failed
copy /y "%SRC%\README.txt"  "%DEST%\" >nul
copy /y "%SRC%\LICENSE"     "%DEST%\" >nul
copy /y "%SRC%\NOTICE"      "%DEST%\" >nul
copy /y "%SRC%\VERSION"     "%DEST%\" >nul
copy /y "%SRC%\uninstall.bat" "%DEST%\" >nul

if /i "%PATHMODE%"=="none" goto :done

if /i "%PATHMODE%"=="machine" (
  for /f "tokens=2,*" %%A in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path 2^>nul ^| find "Path"') do set "OLD=%%B"
  echo !OLD! | find /i "%DEST%\bin" >nul
  if errorlevel 1 setx /m PATH "!OLD!;%DEST%\bin" >nul
) else (
  for /f "tokens=2,*" %%A in ('reg query "HKCU\Environment" /v Path 2^>nul ^| find "Path"') do set "OLD=%%B"
  if not defined OLD set "OLD="
  echo !OLD! | find /i "%DEST%\bin" >nul
  if errorlevel 1 setx PATH "!OLD!;%DEST%\bin" >nul
)

:done
echo.
echo  installed. open a NEW command prompt, then:
echo      icpp "%DEST%\examples\language\01_core_language.icpp"
echo.
exit /b 0

:failed
echo.
echo  INSTALL FAILED while copying. Nothing was added to PATH.
exit /b 1
