@echo off
setlocal enabledelayedexpansion
title PharmaPOS Client Updater
::
:: SmartScreen note:
::   Files downloaded via Invoke-WebRequest get "Mark of the Web" (Zone.Identifier
::   alternate data stream). This script calls Unblock-File on every downloaded and
::   replaced file to strip that mark, so Windows SmartScreen won't block execution.
::   Download itself is never blocked by Windows -- only execution of unrecognized
::   executables triggers SmartScreen. Unblock-File prevents that.
::
echo ============================================
echo   PharmaPOS Client Updater
echo ============================================
echo.

:: =============================================
:: Detect OS architecture (32-bit vs 64-bit)
:: =============================================
set "ARCH_LABEL=32-bit"
set "ARCH=x32"
if "%PROCESSOR_ARCHITECTURE%"=="AMD64" set "ARCH=x64" & set "ARCH_LABEL=64-bit"
if "%PROCESSOR_ARCHITECTURE%"=="IA64"  set "ARCH=x64" & set "ARCH_LABEL=64-bit"
:: Also check PROCESSOR_ARCHITEW6432 (set when 32-bit process runs on 64-bit OS)
if defined PROCESSOR_ARCHITEW6432 set "ARCH=x64" & set "ARCH_LABEL=64-bit"

echo   Detected OS: %ARCH_LABEL%
echo.

:: =============================================
:: Windows 7 SP1 ships PowerShell 2.0, which cannot do TLS 1.2 downloads or
:: Expand-Archive. Detect that and hand over to the HTA updater instead.
:: =============================================
set "PS_MAJOR=0"
for /f "delims=" %%v in ('powershell -NoProfile -Command "$PSVersionTable.PSVersion.Major" 2^>nul') do set "PS_MAJOR=%%v"
if not defined PS_MAJOR set "PS_MAJOR=0"
if %PS_MAJOR% LSS 3 (
    echo.
    echo   PowerShell %PS_MAJOR% detected - Windows 7 default is 2.0.
    echo   This script needs PowerShell 3.0 or later.
    echo   Switching to the Windows 7 compatible updater...
    echo.
    if exist "%~dp0install_update.hta" (
        start "" mshta.exe "%~dp0install_update.hta"
        exit /b 0
    ) else (
        echo   install_update.hta was not found next to this script.
        echo   Please download it from https://installer.pharmapos.com/install_update.hta
        pause
        exit /b 1
    )
)

set "BASE_URL=https://installer.pharmapos.com"
set "DOWNLOAD_URL=%BASE_URL%/%ARCH%"
set "TEMP_DIR=%TEMP%\ppos_update"
set "ZIP_FILE=pp.zip"
set "FILES=ppClient.exe libxl.dll"

:: =============================================
:: Step 1: Create temp directory
:: =============================================
echo [1/6] Preparing download directory...
if exist "%TEMP_DIR%" rmdir /s /q "%TEMP_DIR%"
mkdir "%TEMP_DIR%" 2>nul
if errorlevel 1 (
    echo ERROR: Cannot create temp directory: %TEMP_DIR%
    pause
    exit /b 1
)
echo       Done: %TEMP_DIR%

:: =============================================
:: Step 2: Windows 11 - ensure the MSVC++ runtime (vc_redist)
:: The updater only requests vc_redist on Windows 11. Installs silently with
:: one UAC prompt when the runtime is missing; never blocks the update itself.
:: =============================================
echo.
echo [2/6] Checking Windows 11 Visual C++ runtime...
powershell -NoProfile -Command ^
    "$ErrorActionPreference = 'Continue'; " ^
    "$build = 0; " ^
    "try { $cv = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction Stop; [void][int]::TryParse([string]$cv.CurrentBuildNumber, [ref]$build) } catch {}; " ^
    "if ($build -lt 22000) { Write-Host '      Not Windows 11 - no VC++ runtime check needed.'; exit 0 }; " ^
    "$root = $env:SystemRoot; " ^
    "if ('%ARCH%' -eq 'x64') { if ([Environment]::Is64BitProcess) { $rt = Join-Path $root 'System32' } else { $rt = Join-Path $root 'Sysnative' } } else { if ([Environment]::Is64BitOperatingSystem) { $rt = Join-Path $root 'SysWOW64' } else { $rt = Join-Path $root 'System32' } }; " ^
    "if ((Test-Path (Join-Path $rt 'vcruntime140.dll')) -and (Test-Path (Join-Path $rt 'vcruntime140_1.dll'))) { Write-Host '      Visual C++ runtime already installed.'; exit 0 }; " ^
    "Write-Host '      Visual C++ runtime missing - downloading vc_redist.%ARCH%.exe ...'; " ^
    "$exe = Join-Path '%TEMP_DIR%' 'vc_redist.%ARCH%.exe'; " ^
    "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; " ^
    "try { Invoke-WebRequest -Uri '%BASE_URL%/vc_redist.%ARCH%.exe' -OutFile $exe -UseBasicParsing -ErrorAction Stop; Unblock-File -Path $exe -ErrorAction SilentlyContinue } catch { Write-Host '      WARNING: download failed - you can install it later from %BASE_URL%'; exit 0 }; " ^
    "$logf = Join-Path $env:TEMP 'ppos_vc_redist.log'; " ^
    "$vcArgs = @('/install','/quiet','/norestart','/log',('\"' + $logf + '\"')); " ^
    "$adm = (New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator); " ^
    "try { if ($adm) { $p = Start-Process -FilePath $exe -ArgumentList $vcArgs -Wait -PassThru } else { $p = Start-Process -FilePath $exe -ArgumentList $vcArgs -Verb RunAs -Wait -PassThru } } catch { Write-Host '      WARNING: VC++ runtime install was declined/cancelled - continuing update.'; exit 0 }; " ^
    "$code = $null; try { $code = $p.ExitCode } catch {}; if ($null -eq $code) { if ((Test-Path (Join-Path $rt 'vcruntime140.dll')) -and (Test-Path (Join-Path $rt 'vcruntime140_1.dll'))) { $code = 0 } else { $code = -1 } }; " ^
    "switch ($code) { 0 { Write-Host '      Visual C++ runtime installed.' } 1638 { Write-Host '      Visual C++ runtime already up to date.' } 3010 { Write-Host '      Visual C++ runtime installed - restart recommended.' } 1641 { Write-Host '      Visual C++ runtime installed - restart initiated.' } default { Write-Host ('      WARNING: VC++ runtime install failed (exit code ' + $code + ') - see ' + $logf) } }; " ^
    "exit 0"

:: =============================================
:: Step 3: Download pp.zip
:: =============================================
echo.
echo [3/6] Downloading %ZIP_FILE% from %DOWNLOAD_URL%...
powershell -NoProfile -Command ^
    "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; " ^
    "try { " ^
    "  Invoke-WebRequest -Uri '%DOWNLOAD_URL%/%ZIP_FILE%' -OutFile '%TEMP_DIR%\%ZIP_FILE%' -UseBasicParsing; " ^
    "  if ((Get-Item '%TEMP_DIR%\%ZIP_FILE%').Length -eq 0) { throw 'Empty file' } " ^
    "} catch { " ^
    "  Write-Host 'ERROR downloading %ZIP_FILE%: ' -NoNewline; Write-Host $_.Exception.Message; " ^
    "  exit 1 " ^
    "}"
if errorlevel 1 (
    echo       FAILED to download %ZIP_FILE%
    pause
    exit /b 1
)
echo       OK: %ZIP_FILE%

:: =============================================
:: Step 4: Extract pp.zip
:: =============================================
echo.
echo [4/6] Extracting %ZIP_FILE%...
powershell -NoProfile -Command ^
    "try { " ^
    "  Expand-Archive -Path '%TEMP_DIR%\%ZIP_FILE%' -DestinationPath '%TEMP_DIR%' -Force; " ^
    "  @('ppClient.exe','libxl.dll') | ForEach-Object { " ^
    "    $p = Join-Path '%TEMP_DIR%' $_; " ^
    "    if (Test-Path $p) { Unblock-File -Path $p -ErrorAction SilentlyContinue; Write-Host \"      OK: $_\" } " ^
    "    else { Write-Host \"      WARNING: $_ not found in zip!\" } " ^
    "  } " ^
    "} catch { " ^
    "  Write-Host 'ERROR extracting: ' -NoNewline; Write-Host $_.Exception.Message; " ^
    "  exit 1 " ^
    "}"
if errorlevel 1 (
    echo       FAILED to extract %ZIP_FILE%
    pause
    exit /b 1
)
echo       Extraction complete.

:: =============================================
:: Step 5: Find desktop shortcuts -> replace in target folders
:: =============================================
echo.
echo [5/6] Finding shortcuts (Desktop + Taskbar) that launch ppClient.exe...

:: Use PowerShell to find all .lnk shortcuts pointing to ppClient.exe,
:: extract their parent directories (deduplicated), and replace files.
powershell -NoProfile -Command ^
    "$WshShell = New-Object -ComObject WScript.Shell; " ^
    "$desktops = @([Environment]::GetFolderPath('Desktop'), [Environment]::GetFolderPath('CommonDesktop'), (Join-Path $env:APPDATA 'Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar')); " ^
    "$targetDirs = @{}; " ^
    "$Files = @('ppClient.exe','libxl.dll'); " ^
    "foreach ($desk in $desktops) { " ^
    "  if (-not (Test-Path $desk)) { continue }; " ^
    "  Write-Host \"      Scanning $desk ...\"; " ^
    "  Get-ChildItem -Path $desk -Filter '*.lnk' -ErrorAction SilentlyContinue | ForEach-Object { " ^
    "    try { " ^
    "      $sc = $WshShell.CreateShortcut($_.FullName); " ^
    "      if ($sc.TargetPath -and (Split-Path $sc.TargetPath -Leaf) -eq 'ppClient.exe') { " ^
    "        $d = Split-Path $sc.TargetPath -Parent; " ^
    "        if ($d -and -not $targetDirs.ContainsKey($d)) { " ^
    "          $targetDirs[$d] = $true; " ^
    "          Write-Host \"         Shortcut: $($_.Name) -> $d\\\" " ^
    "        } " ^
    "      } " ^
    "    } catch {} " ^
    "  } " ^
    "}; " ^
    "Write-Host \"      Found $($targetDirs.Count) shortcut(s)\"; " ^
    "if ($targetDirs.Count -eq 0) { " ^
    "  Write-Host \"      WARNING: No shortcuts found. Nothing to update.\"; " ^
    "  exit 1 " ^
    "}; " ^
    "$replaced = 0; " ^
    "foreach ($dir in $targetDirs.Keys) { " ^
    "  Write-Host \"      Updating: $dir\\\"; " ^
    "  foreach ($f in $Files) { " ^
    "    try { " ^
    "      Copy-Item -Path '%TEMP_DIR%\\$f' -Destination \"$dir\\$f\" -Force -ErrorAction Stop; " ^
    "      Unblock-File -Path \"$dir\\$f\" -ErrorAction SilentlyContinue; " ^
    "      Write-Host \"         OK: $f\"; " ^
    "      $replaced++ " ^
    "    } catch { " ^
    "      Write-Host \"         WARNING: Could not replace $f - $_\" " ^
    "    } " ^
    "  } " ^
    "}; " ^
    "Write-Host \"      Updated $replaced file(s) across $($targetDirs.Count) folder(s).\" "

if errorlevel 1 (
    echo       Shortcut scan failed or no targets found.
)

echo       Shortcut scan complete.
goto :done

:: =============================================
:: Step 6: Cleanup
:: =============================================
:done
echo.
echo [6/6] Cleaning up...
rmdir /s /q "%TEMP_DIR%" 2>nul
echo       Done.

echo.
echo ============================================
echo   Update Complete!
echo ============================================
echo.
echo   Press any key to exit...
pause >nul
endlocal
exit /b 0
