@echo off
setlocal enabledelayedexpansion

:: ============================================================================
::  webSlinger Native Components Installer
::  Copyright (c) 2025 Gradient Research LLC
::  All rights reserved.
:: ============================================================================

echo.
echo ======================================================================
echo   webSlinger Native Components Installer
echo ======================================================================
echo.

:: ----------------------------------------------------------------------------
:: Configuration
:: ----------------------------------------------------------------------------
set "INSTALL_DIR=%LOCALAPPDATA%\webSlinger"
set "KEYBUNKER_DIR=%LOCALAPPDATA%\webSlinger\KeyBunkerBridge"
set "WEBSLINGER_EXT_ID=bngmcojedjppiikpmffnklhfkmoecdch"
set "KEYCOCOON_EXT_ID=ajakidlpiolaajjnkmhijbnnpmmcgffe"
set "INSTALLER_VERSION=1.1.4"

:: Get the directory where setup.bat is located (the extracted ZIP)
set "SOURCE_DIR=%~dp0"
:: Remove trailing backslash
if "%SOURCE_DIR:~-1%"=="\" set "SOURCE_DIR=%SOURCE_DIR:~0,-1%"

:: ----------------------------------------------------------------------------
:: Step 1: Detect Chrome extensions
:: ----------------------------------------------------------------------------
echo [1/10] Detecting Chrome extensions...

set "WEBSLINGER_FOUND=0"
set "KEYCOCOON_FOUND=0"
set "CHROME_DATA=%LOCALAPPDATA%\Google\Chrome\User Data"

if not exist "!CHROME_DATA!" (
    echo.
    echo ERROR: Chrome user data directory not found.
    echo Expected: !CHROME_DATA!
    echo Please ensure Google Chrome is installed.
    echo.
    pause
    exit /b 1
)

for /d %%P in ("!CHROME_DATA!\*") do (
    if exist "%%P\Extensions\!WEBSLINGER_EXT_ID!" (
        set "WEBSLINGER_FOUND=1"
    )
    if exist "%%P\Extensions\!KEYCOCOON_EXT_ID!" (
        set "KEYCOCOON_FOUND=1"
    )
)

if "%WEBSLINGER_FOUND%"=="0" (
    echo.
    echo WARNING: webSlinger extension not detected in Chrome.
    echo.
    echo If you have installed webSlinger from the Chrome Web Store,
    echo please enter the extension ID below.
    echo Otherwise press Enter to abort.
    echo.
    set /p "CUSTOM_ID=Extension ID: "
    if "!CUSTOM_ID!"=="" (
        echo.
        echo Installation aborted. Please install the webSlinger extension first.
        echo.
        pause
        exit /b 1
    )
    set "WEBSLINGER_EXT_ID=!CUSTOM_ID!"
    echo Using extension ID: !WEBSLINGER_EXT_ID!
) else (
    echo   webSlinger extension found.
)

if "%KEYCOCOON_FOUND%"=="1" (
    echo   keyCocoon extension found.
) else (
    echo   keyCocoon extension not found - keyBunker will not be installed.
)
echo.

:: ----------------------------------------------------------------------------
:: Step 2: Verify source files exist
:: ----------------------------------------------------------------------------
echo [2/10] Verifying source files...

if not exist "!SOURCE_DIR!\python\python.exe" (
    echo ERROR: Bundled Python not found at !SOURCE_DIR!\python\python.exe
    echo Please ensure you extracted the complete ZIP file.
    pause
    exit /b 1
)

if not exist "!SOURCE_DIR!\taskSpinner\taskSpinner.py" (
    echo ERROR: taskSpinner.py not found at !SOURCE_DIR!\taskSpinner\taskSpinner.py
    pause
    exit /b 1
)

echo   Source files verified.
echo.

:: ----------------------------------------------------------------------------
:: Step 3: Create directory structure
:: ----------------------------------------------------------------------------
echo [3/10] Creating directory structure...

if not exist "!INSTALL_DIR!" mkdir "!INSTALL_DIR!"
if not exist "!INSTALL_DIR!\python" mkdir "!INSTALL_DIR!\python"
if not exist "!INSTALL_DIR!\site-packages" mkdir "!INSTALL_DIR!\site-packages"
if not exist "!INSTALL_DIR!\taskSpinner" mkdir "!INSTALL_DIR!\taskSpinner"
if not exist "!INSTALL_DIR!\taskSpinner\scheduledTasks" mkdir "!INSTALL_DIR!\taskSpinner\scheduledTasks"
if not exist "!INSTALL_DIR!\taskSpinner\outputData" mkdir "!INSTALL_DIR!\taskSpinner\outputData"
if not exist "!INSTALL_DIR!\taskSpinner\logs" mkdir "!INSTALL_DIR!\taskSpinner\logs"

if "!KEYCOCOON_FOUND!"=="1" (
    if not exist "!KEYBUNKER_DIR!" mkdir "!KEYBUNKER_DIR!"
)

echo   Directories created.
echo.

:: ----------------------------------------------------------------------------
:: Step 4: Copy files
:: ----------------------------------------------------------------------------
echo [4/10] Copying files...

:: Copy Python runtime
echo   Copying Python runtime...
xcopy "!SOURCE_DIR!\python" "!INSTALL_DIR!\python\" /E /I /Y /Q >nul 2>&1

:: Copy site-packages
if exist "!SOURCE_DIR!\site-packages" (
    echo   Copying Python packages...
    xcopy "!SOURCE_DIR!\site-packages" "!INSTALL_DIR!\site-packages\" /E /I /Y /Q >nul 2>&1
) else (
    echo   WARNING: site-packages not found at !SOURCE_DIR!\site-packages
)

:: Copy taskSpinner
echo   Copying taskSpinner...
copy /Y "!SOURCE_DIR!\taskSpinner\taskSpinner.py" "!INSTALL_DIR!\taskSpinner\taskSpinner.py" >nul

:: Copy uninstaller
echo   Copying uninstaller...
copy /Y "!SOURCE_DIR!\uninstall.bat" "!INSTALL_DIR!\uninstall.bat" >nul

:: Copy keyBunker files (if keyCocoon detected)
if "!KEYCOCOON_FOUND!"=="1" (
    echo   Copying keyBunker...
    copy /Y "!SOURCE_DIR!\keyCocoon\keyBunker.py" "!KEYBUNKER_DIR!\keyBunker.py" >nul
    copy /Y "!SOURCE_DIR!\keyCocoon\keybunker_daemon.py" "!KEYBUNKER_DIR!\keybunker_daemon.py" >nul
    copy /Y "!SOURCE_DIR!\keyCocoon\keybunker_helper.py" "!KEYBUNKER_DIR!\keybunker_helper.py" >nul
    if exist "!SOURCE_DIR!\icons\keyBunker.ico" (
        copy /Y "!SOURCE_DIR!\icons\keyBunker.ico" "!KEYBUNKER_DIR!\keyBunker.ico" >nul
        echo   Copied keyBunker icon.
    )
)

echo   Files copied.
echo.

:: ----------------------------------------------------------------------------
:: Step 5: Generate batch wrappers
:: ----------------------------------------------------------------------------
echo [5/10] Generating batch wrappers...

:: taskSpinner.bat
(
    echo @echo off
    echo set PYTHONPATH=!INSTALL_DIR!\site-packages
    echo cd /d "!INSTALL_DIR!\taskSpinner"
    echo "!INSTALL_DIR!\python\python.exe" -B taskSpinner.py %%*
) > "!INSTALL_DIR!\taskSpinner\taskSpinner.bat"

echo   Created taskSpinner.bat

:: keyBunker wrappers (if keyCocoon detected)
if "!KEYCOCOON_FOUND!"=="0" goto :skip_keybunker_wrappers

:: keybunker_helper.bat (native messaging host)
(
    echo @echo off
    echo set PYTHONPATH=!INSTALL_DIR!\site-packages
    echo cd /d "!KEYBUNKER_DIR!"
    echo "!INSTALL_DIR!\python\python.exe" -B keybunker_helper.py %%*
) > "!KEYBUNKER_DIR!\keybunker_helper.bat"

echo   Created keybunker_helper.bat

:: Copy the launcher wrapper script
copy /Y "!SOURCE_DIR!\keyCocoon\launch_keyBunker.py" "!KEYBUNKER_DIR!\launch_keyBunker.py" >nul
echo   Copied launch_keyBunker.py

:: keyBunker.vbs (GUI launcher - no console window)
echo Set WshShell = CreateObject("WScript.Shell") > "!KEYBUNKER_DIR!\keyBunker.vbs"
echo Set env = WshShell.Environment("Process") >> "!KEYBUNKER_DIR!\keyBunker.vbs"
echo env("PYTHONPATH") = "!INSTALL_DIR!\site-packages" >> "!KEYBUNKER_DIR!\keyBunker.vbs"
echo WshShell.CurrentDirectory = "!KEYBUNKER_DIR!" >> "!KEYBUNKER_DIR!\keyBunker.vbs"
echo WshShell.Run """!INSTALL_DIR!\python\python.exe"" -B launch_keyBunker.py", 1, True >> "!KEYBUNKER_DIR!\keyBunker.vbs"
echo Set WshShell = Nothing >> "!KEYBUNKER_DIR!\keyBunker.vbs"

echo   Created keyBunker.vbs

:skip_keybunker_wrappers
echo.

:: ----------------------------------------------------------------------------
:: Step 6: Generate run_hidden.vbs for scheduled task
:: ----------------------------------------------------------------------------
echo [6/10] Generating scheduled task helper...

echo Set WshShell = CreateObject("WScript.Shell") > "!INSTALL_DIR!\taskSpinner\run_hidden.vbs"
echo WshShell.Run """!INSTALL_DIR!\taskSpinner\taskSpinner.bat"" --check-and-execute", 0, False >> "!INSTALL_DIR!\taskSpinner\run_hidden.vbs"
echo Set WshShell = Nothing >> "!INSTALL_DIR!\taskSpinner\run_hidden.vbs"

echo   Created run_hidden.vbs
echo.

:: ----------------------------------------------------------------------------
:: Step 7: Generate native messaging manifests
:: ----------------------------------------------------------------------------
echo [7/10] Generating native messaging manifests...

:: taskSpinner manifest
:: Need to escape backslashes for JSON
set "TS_BAT_PATH=!INSTALL_DIR!\taskSpinner\taskSpinner.bat"
set "TS_BAT_JSON=!TS_BAT_PATH:\=\\!"

(
    echo {
    echo     "name": "com.webslinger.taskspinner",
    echo     "description": "taskSpinner - webSlinger file operations and task scheduling",
    echo     "path": "!TS_BAT_JSON!",
    echo     "type": "stdio",
    echo     "allowed_origins": ["chrome-extension://!WEBSLINGER_EXT_ID!/"]
    echo }
) > "!INSTALL_DIR!\taskSpinner\com.webslinger.taskspinner.json"

echo   Created com.webslinger.taskspinner.json

:: keyBunker manifest (if keyCocoon detected)
if "!KEYCOCOON_FOUND!"=="0" goto :skip_keybunker_manifest

set "KB_BAT_PATH=!KEYBUNKER_DIR!\keybunker_helper.bat"
set "KB_BAT_JSON=!KB_BAT_PATH:\=\\!"

(
    echo {
    echo     "name": "com.keybunker.helper",
    echo     "description": "KeyBunker credential helper for keyCocoon",
    echo     "path": "!KB_BAT_JSON!",
    echo     "type": "stdio",
    echo     "allowed_origins": ["chrome-extension://!KEYCOCOON_EXT_ID!/"]
    echo }
) > "!KEYBUNKER_DIR!\com.keybunker.helper.json"

echo   Created com.keybunker.helper.json

:skip_keybunker_manifest
echo.

:: ----------------------------------------------------------------------------
:: Step 8: Write registry entries
:: ----------------------------------------------------------------------------
echo [8/10] Configuring Chrome native messaging...

set "TS_MANIFEST=!INSTALL_DIR!\taskSpinner\com.webslinger.taskspinner.json"
REG ADD "HKCU\SOFTWARE\Google\Chrome\NativeMessagingHosts\com.webslinger.taskspinner" /ve /t REG_SZ /d "!TS_MANIFEST!" /f >nul 2>&1

if !ERRORLEVEL! EQU 0 (
    echo   Registered com.webslinger.taskspinner
) else (
    echo   WARNING: Failed to register com.webslinger.taskspinner
)

if "!KEYCOCOON_FOUND!"=="0" goto :skip_keybunker_registry

set "KB_MANIFEST=!KEYBUNKER_DIR!\com.keybunker.helper.json"
REG ADD "HKCU\SOFTWARE\Google\Chrome\NativeMessagingHosts\com.keybunker.helper" /ve /t REG_SZ /d "!KB_MANIFEST!" /f >nul 2>&1

if !ERRORLEVEL! EQU 0 (
    echo   Registered com.keybunker.helper
) else (
    echo   WARNING: Failed to register com.keybunker.helper
)

:skip_keybunker_registry
echo.

:: ----------------------------------------------------------------------------
:: Step 9: Create Windows scheduled task
:: ----------------------------------------------------------------------------
echo [9/10] Creating scheduled task...

schtasks /create /tn "webSlinger_TaskSpinner" /tr "wscript.exe \"!INSTALL_DIR!\taskSpinner\run_hidden.vbs\"" /sc minute /mo 5 /ru "!USERNAME!" /rl limited /f >nul 2>&1

if !ERRORLEVEL! EQU 0 (
    echo   Created scheduled task: webSlinger_TaskSpinner (every 5 minutes)
) else (
    echo   WARNING: Failed to create scheduled task.
    echo   You may need to run this installer as administrator for this step.
)
echo.

:: ----------------------------------------------------------------------------
:: Step 10: Create Start Menu entry and version file
:: ----------------------------------------------------------------------------
echo [10/10] Finalizing installation...

:: Write version file
echo !INSTALLER_VERSION!> "!INSTALL_DIR!\version.txt"
echo   Wrote version file: !INSTALLER_VERSION!

:: Create Start Menu shortcut for keyBunker
if "!KEYCOCOON_FOUND!"=="0" goto :skip_start_menu

set "START_MENU=!APPDATA!\Microsoft\Windows\Start Menu\Programs\webSlinger"
set "SHORTCUT_VBS=!TEMP!\create_shortcut.vbs"
set "ICON_PATH=!KEYBUNKER_DIR!\keyBunker.ico"

:: Write VBScript to create shortcut (line by line to avoid parentheses issues)
echo Set ws = CreateObject("WScript.Shell") > "!SHORTCUT_VBS!"
echo Set fso = CreateObject("Scripting.FileSystemObject") >> "!SHORTCUT_VBS!"
echo startFolder = "!START_MENU!" >> "!SHORTCUT_VBS!"
echo If Not fso.FolderExists(startFolder) Then fso.CreateFolder(startFolder) >> "!SHORTCUT_VBS!"
echo Set sc = ws.CreateShortcut(startFolder ^& "\KeyBunker.lnk") >> "!SHORTCUT_VBS!"
echo sc.TargetPath = "wscript.exe" >> "!SHORTCUT_VBS!"
echo sc.Arguments = """"!KEYBUNKER_DIR!\keyBunker.vbs"""" >> "!SHORTCUT_VBS!"
echo sc.WorkingDirectory = "!KEYBUNKER_DIR!" >> "!SHORTCUT_VBS!"
echo sc.Description = "KeyBunker Credential Manager" >> "!SHORTCUT_VBS!"
echo sc.WindowStyle = 7 >> "!SHORTCUT_VBS!"
echo sc.IconLocation = "!ICON_PATH!" >> "!SHORTCUT_VBS!"
echo sc.Save >> "!SHORTCUT_VBS!"

cscript //nologo "!SHORTCUT_VBS!" >nul 2>&1
del "!SHORTCUT_VBS!" >nul 2>&1

if exist "!START_MENU!\KeyBunker.lnk" (
    echo   Created Start Menu entry: webSlinger ^> KeyBunker
) else (
    echo   WARNING: Failed to create Start Menu shortcut.
)

:skip_start_menu

:: Create Start Menu shortcut for Uninstall (always)
set "START_MENU=!APPDATA!\Microsoft\Windows\Start Menu\Programs\webSlinger"
set "UNINSTALL_VBS=!TEMP!\create_uninstall_shortcut.vbs"

echo Set ws = CreateObject("WScript.Shell") > "!UNINSTALL_VBS!"
echo Set fso = CreateObject("Scripting.FileSystemObject") >> "!UNINSTALL_VBS!"
echo startFolder = "!START_MENU!" >> "!UNINSTALL_VBS!"
echo If Not fso.FolderExists(startFolder) Then fso.CreateFolder(startFolder) >> "!UNINSTALL_VBS!"
echo Set sc = ws.CreateShortcut(startFolder ^& "\Uninstall Native Components.lnk") >> "!UNINSTALL_VBS!"
echo sc.TargetPath = "!INSTALL_DIR!\uninstall.bat" >> "!UNINSTALL_VBS!"
echo sc.WorkingDirectory = "!INSTALL_DIR!" >> "!UNINSTALL_VBS!"
echo sc.Description = "Uninstall keyBunker, taskSpinner, and bundled Python" >> "!UNINSTALL_VBS!"
echo sc.Save >> "!UNINSTALL_VBS!"

cscript //nologo "!UNINSTALL_VBS!" >nul 2>&1
del "!UNINSTALL_VBS!" >nul 2>&1

if exist "!START_MENU!\Uninstall Native Components.lnk" (
    echo   Created Start Menu entry: webSlinger ^> Uninstall Native Components
) else (
    echo   WARNING: Failed to create Uninstall shortcut.
)

:: ============================================================================
:: Installation Summary
:: ============================================================================
echo.
echo ======================================================================
echo   Installation Complete
echo ======================================================================
echo.
echo   Install location:  !INSTALL_DIR!
echo   Python runtime:    !INSTALL_DIR!\python
echo   taskSpinner:       !INSTALL_DIR!\taskSpinner
if "!KEYCOCOON_FOUND!"=="1" (
    echo   keyBunker:         !KEYBUNKER_DIR!
    echo   Start Menu:        webSlinger ^> KeyBunker
)
echo   Start Menu:        webSlinger ^> Uninstall Native Components
echo   Scheduled task:    webSlinger_TaskSpinner (every 5 minutes)
echo   Version:           !INSTALLER_VERSION!
echo.
echo   Next steps:
echo     1. Restart Chrome to activate native messaging
echo     2. The webSlinger extension should now detect taskSpinner
if "!KEYCOCOON_FOUND!"=="1" (
    echo     3. Launch KeyBunker from the Start Menu to manage credentials
)
echo.
echo ======================================================================
echo.

pause
endlocal
