@echo off
setlocal EnableExtensions

set "SOURCE_ROOT=%~dp0"
set "INSTALL_ROOT=%USERPROFILE%\MurtCoPdfDrag"
set "INSTALLED_HOST=%INSTALL_ROOT%\host"
set "INSTALLED_EXTENSION=%INSTALL_ROOT%\extension"
set "HOST_EXE=%INSTALLED_HOST%\MurtCoDragHost.exe"
set "HOST_MANIFEST=%INSTALLED_HOST%\com.willett.murtco_drag.json"

if not exist "%SOURCE_ROOT%host\MurtCoDragHost.exe" (
  echo ERROR: The packaged native helper is missing.
  pause
  exit /b 1
)
if not exist "%SOURCE_ROOT%extension\manifest.json" (
  echo ERROR: The packaged browser extension is missing.
  pause
  exit /b 1
)

taskkill /F /IM MurtCoDragHost.exe >nul 2>&1

if exist "%INSTALLED_HOST%" rmdir /S /Q "%INSTALLED_HOST%"
if exist "%INSTALLED_EXTENSION%" rmdir /S /Q "%INSTALLED_EXTENSION%"
mkdir "%INSTALLED_HOST%" >nul 2>&1
mkdir "%INSTALLED_EXTENSION%" >nul 2>&1
if errorlevel 1 (
  echo ERROR: Could not create the per-user installation folder:
  echo   %INSTALL_ROOT%
  pause
  exit /b 1
)

xcopy "%SOURCE_ROOT%host\*" "%INSTALLED_HOST%\" /E /I /Y /Q >nul
if errorlevel 1 (
  echo ERROR: Could not install the native helper.
  pause
  exit /b 1
)
xcopy "%SOURCE_ROOT%extension\*" "%INSTALLED_EXTENSION%\" /E /I /Y /Q >nul
if errorlevel 1 (
  echo ERROR: Could not install the browser extension.
  pause
  exit /b 1
)

copy /Y "%SOURCE_ROOT%Uninstall-MurtCo-Pdf-Drag.cmd" "%INSTALL_ROOT%\" >nul
copy /Y "%SOURCE_ROOT%Collect-MurtCo-Pdf-Drag-Logs.cmd" "%INSTALL_ROOT%\" >nul
copy /Y "%SOURCE_ROOT%README.txt" "%INSTALL_ROOT%\" >nul

"%HOST_EXE%" --register "%HOST_MANIFEST%"
if errorlevel 1 (
  echo ERROR: Edge and Chrome native-host registration failed.
  pause
  exit /b 1
)

echo %INSTALLED_EXTENSION%| clip

set "EDGE=%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe"
if not exist "%EDGE%" set "EDGE=%ProgramFiles%\Microsoft\Edge\Application\msedge.exe"
set "CHROME=%ProgramFiles%\Google\Chrome\Application\chrome.exe"
if not exist "%CHROME%" set "CHROME=%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe"

if exist "%EDGE%" (
  start "" "%EDGE%" "edge://extensions/"
) else if exist "%CHROME%" (
  start "" "%CHROME%" "chrome://extensions/"
)

echo.
echo MurtCo PDF Drag Pilot 0.3.7 is ready in this Windows user's home folder.
echo.
echo Installed extension folder copied to the clipboard:
echo   %INSTALLED_EXTENSION%
echo.
echo In Microsoft Edge:
echo   1. Open edge://extensions/
echo   2. Remove the earlier WIS-225/MurtCo PDF Drag proof if it is listed.
echo   3. Enable Developer mode.
echo   4. Select Load unpacked.
echo   5. Paste the extension folder path and select it.
echo.
echo In Google Chrome, use the same steps at chrome://extensions/.
echo Install the extension in only the browser profiles that should use MurtCo.
pause
