@echo off
setlocal EnableExtensions

REM Auto-detect Program Files path
IF DEFINED PROCESSOR_ARCHITEW6432 (
  REM Running 32-bit process on 64-bit Windows
  set "APP_DIR=%ProgramFiles(x86)%\DirectPay"
) ELSE IF "%PROCESSOR_ARCHITECTURE%"=="AMD64" (
  REM Running 64-bit process on 64-bit Windows
  set "APP_DIR=%ProgramFiles%\DirectPay"
) ELSE (
  REM 32-bit Windows
  set "APP_DIR=%ProgramFiles%\DirectPay"
)

set "GPG_EXE=%APP_DIR%\GnuPG\gpg.exe"
set "GNUPG_HOME=%ProgramData%\DirectPay\GnuPG"
set "KEY_ASC=%APP_DIR%\Martha Walker.asc"

REM --- pick a log path that always works ---
if not exist "%GNUPG_HOME%" mkdir "%GNUPG_HOME%" 2>nul
set "LOG=%GNUPG_HOME%\postinstall.log"
if not exist "%GNUPG_HOME%" set "LOG=%TEMP%\DirectPay_postinstall.log"

echo [%DATE% %TIME%] PostInstall starting...>>"%LOG%"

if not exist "%GPG_EXE%" (echo [%DATE% %TIME%] ERROR: gpg.exe not found at "%GPG_EXE%".>>"%LOG%" & exit /b 1)
if not exist "%KEY_ASC%" (echo [%DATE% %TIME%] ERROR: key file missing at "%KEY_ASC%".>>"%LOG%" & exit /b 1)

REM --- ensure ProgramData homedir exists and is writable for all users ---
mkdir "%GNUPG_HOME%" 2>nul
icacls "%GNUPG_HOME%" /inheritance:e >nul 2>&1
icacls "%GNUPG_HOME%" /grant *S-1-5-32-545:(OI)(CI)M >nul 2>&1
icacls "%GNUPG_HOME%" /grant *S-1-5-32-544:(OI)(CI)F >nul 2>&1
icacls "%GNUPG_HOME%" /grant SYSTEM:(OI)(CI)F        >nul 2>&1

REM --- rebind LOG to the canonical location once folder is guaranteed to exist ---
set "LOG=%GNUPG_HOME%\postinstall.log"
echo [%DATE% %TIME%] Using homedir "%GNUPG_HOME%">>"%LOG%"

"%GPG_EXE%" --homedir "%GNUPG_HOME%" --list-keys "mwalker@westpac.com.au" >nul 2>&1
if %errorlevel%==0 (
  echo [%DATE% %TIME%] Key already present.>>"%LOG%"
) else (
  echo [%DATE% %TIME%] Importing key...>>"%LOG%"
  "%GPG_EXE%" --homedir "%GNUPG_HOME%" --import "%KEY_ASC%" >>"%LOG%" 2>&1
  if errorlevel 1 (echo [%DATE% %TIME%] ERROR: import failed.>>"%LOG%" & exit /b 1)
  echo [%DATE% %TIME%] Import successful.>>"%LOG%"
)

echo [%DATE% %TIME%] PostInstall completed.>>"%LOG%"
exit /b 0