# TNG eWallet bypass: install xposed + LSPosed scope + optional clear app data
param(
    [switch]$ClearTng,
    [switch]$SkipBuild
)

$ErrorActionPreference = "Stop"
$ProjectRoot = Split-Path -Parent $PSScriptRoot
Set-Location $ProjectRoot

$sdk = "C:\Users\Administrator\AppData\Local\Android\Sdk"
$adb = Join-Path $sdk "platform-tools\adb.exe"
if (-not (Test-Path $adb)) { $adb = "adb" }

if (-not $SkipBuild) {
    & "$ProjectRoot\scripts\build-debug.ps1"
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}

$xposedApk = Join-Path $ProjectRoot "xposed-module\build\outputs\apk\debug\xposed-module-debug.apk"
Write-Host "=== Install Xposed module ===" -ForegroundColor Cyan
& $adb install -r -t -g $xposedApk
if ($LASTEXITCODE -ne 0) {
    & $adb install -r -t -g --bypass-low-target-sdk-block $xposedApk
}

Write-Host "=== Configure LSPosed scope (incl. TNG) ===" -ForegroundColor Cyan
$apkPath = (& $adb shell pm path com.miraclegarden.smsmessage.xposed) -replace '^package:', ''
$apkPath = $apkPath.Trim()
& $adb shell "su -c 'cp /data/adb/lspd/config/modules_config.db /sdcard/Download/modules_config.db; rm -f /data/adb/lspd/config/modules_config.db-wal /data/adb/lspd/config/modules_config.db-shm'"
$db = Join-Path $env:TEMP "modules_config_tng_finish.db"
& $adb pull /sdcard/Download/modules_config.db $db
python "$ProjectRoot\scripts\configure-lsposed.py" $db $apkPath
& $adb push $db /sdcard/Download/modules_config.db
& $adb shell "su -c 'cp /sdcard/Download/modules_config.db /data/adb/lspd/config/modules_config.db; rm -f /data/adb/lspd/config/modules_config.db-wal /data/adb/lspd/config/modules_config.db-shm; chmod 660 /data/adb/lspd/config/modules_config.db'"

Write-Host "=== Phone checklist ===" -ForegroundColor Yellow
Write-Host "  1. TNG must NOT be in Magisk DenyList (DenyList blocks Vector/LSPosed injection)"
Write-Host "  2. MariBank/Seabank may stay on DenyList; Shamiko + ProcMaps hook hide root for them"
Write-Host "  3. LSPosed: notiMessage Xposed enabled, scope includes my.com.tngdigital.ewallet"
Write-Host "  4. LSPosed soft reboot / zygote restart after scope update"
Write-Host "  5. Disable USB debugging before test (recommended)"

if ($ClearTng) {
    Write-Host "=== Clear TNG data ===" -ForegroundColor Cyan
    & $adb shell "su -c 'pm clear my.com.tngdigital.ewallet'"
}

& $adb shell "am force-stop my.com.tngdigital.ewallet"
Write-Host ""
Write-Host "Done. Launch TNG eWallet, then run: .\scripts\logcat-tng.ps1" -ForegroundColor Green
