@echo off
setlocal EnableExtensions

set "HOST_DIR=%SystemDrive%\HJXH\folder-native-host"
set "HOST_CS=%HOST_DIR%\hjxh-folder-native-host.cs"
set "HOST_EXE=%HOST_DIR%\hjxh-folder-native-host.exe"
set "HOST_JSON=%HOST_DIR%\com.hjxh.folder_opener.json"
set "EXTENSION_ID=mnegiljggknganflilabnbkhnmnaapmb"

if not exist "%HOST_DIR%" mkdir "%HOST_DIR%" >nul 2>nul
if errorlevel 1 (
  echo Failed to create %HOST_DIR%.
  pause
  exit /b 1
)

set "HOST_CS_PATH=%HOST_CS%"
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ^
  "$source = Join-Path (Get-Location) 'hjxh-folder-native-host.cs'; if (Test-Path $source) { Copy-Item -LiteralPath $source -Destination $env:HOST_CS_PATH -Force; exit 0 }; Invoke-WebRequest -UseBasicParsing 'https://hjxh-zhoubao-gallery.pages.dev/tools/hjxh-folder-native-host.cs' -OutFile $env:HOST_CS_PATH"

if errorlevel 1 (
  echo Failed to install native host source.
  pause
  exit /b 1
)

powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ^
  "Add-Type -TypeDefinition (Get-Content -LiteralPath '%HOST_CS%' -Raw) -OutputAssembly '%HOST_EXE%' -OutputType ConsoleApplication"

if errorlevel 1 (
  echo Failed to build native host executable.
  pause
  exit /b 1
)

powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ^
  "$manifest = @{ name='com.hjxh.folder_opener'; description='HJXH folder opener native host'; path='%HOST_EXE%'; type='stdio'; allowed_origins=@('chrome-extension://%EXTENSION_ID%/') }; $manifest | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath '%HOST_JSON%' -Encoding UTF8"

if errorlevel 1 (
  echo Failed to write native host manifest.
  pause
  exit /b 1
)

reg add "HKCU\Software\Google\Chrome\NativeMessagingHosts\com.hjxh.folder_opener" /ve /d "%HOST_JSON%" /f >nul
reg add "HKCU\Software\Microsoft\Edge\NativeMessagingHosts\com.hjxh.folder_opener" /ve /d "%HOST_JSON%" /f >nul

echo HJXH native folder opener installed.
echo Please reload the HJXH browser extension, then click Open file directory again.
pause
