@echo off
setlocal

if not "%~1"=="" goto launch

set "INSTALL_DIR=%LOCALAPPDATA%\WarehouseRemoteTools"
set "TARGET=%INSTALL_DIR%\warehouse-remote-tools.cmd"
if not exist "%INSTALL_DIR%" mkdir "%INSTALL_DIR%"
copy /Y "%~f0" "%TARGET%" >nul

for %%S in (warehouse-ssh warehouse-winbox) do (
  reg add "HKCU\Software\Classes\%%S" /ve /d "URL:%%S" /f >nul
  reg add "HKCU\Software\Classes\%%S" /v "URL Protocol" /d "" /f >nul
  reg add "HKCU\Software\Classes\%%S\shell\open\command" /ve /d "\"%TARGET%\" \"%%1\"" /f >nul
)

echo Warehouse SSH and WinBox browser launchers are installed for this Windows user.
echo Return to the site and press SSH or WinBox again.
pause
exit /b 0

:launch
set "WAREHOUSE_REMOTE_URI=%~1"
powershell.exe -NoProfile -Command "$u=[Uri]$env:WAREHOUSE_REMOTE_URI; $h=$u.Host; if($h -notmatch '^[A-Za-z0-9.:%_-]+$'){throw 'Unsupported host'}; if($u.Scheme -eq 'warehouse-ssh'){Start-Process -FilePath 'wt.exe' -ArgumentList @('ssh',('admin@'+$h))}elseif($u.Scheme -eq 'warehouse-winbox'){Start-Process -FilePath 'winbox.exe' -ArgumentList @($h,'admin')}else{throw 'Unsupported protocol'}"
exit /b %ERRORLEVEL%
