# MariBank SG register test — new identity, optional log capture
param(
    [switch]$NewIdentity,
    [switch]$CaptureLog,
    [switch]$DumpLog,
    [switch]$InstallModule,
    [switch]$DisableUsbDebug,
    [switch]$KeepAdb,
    [switch]$All
)

$ErrorActionPreference = "Stop"
$ProjectRoot = Split-Path -Parent $PSScriptRoot
$Pkg = "sg.com.maribankmobile.digitalbank"

function Resolve-AdbPath {
    $candidates = @(
        (Join-Path $env:LOCALAPPDATA "Android\Sdk\platform-tools\adb.exe"),
        "C:\Users\Administrator\AppData\Local\Android\Sdk\platform-tools\adb.exe"
    )
    foreach ($path in $candidates) {
        if (Test-Path $path) { return $path }
    }
    $cmd = Get-Command adb -ErrorAction SilentlyContinue
    if ($cmd) { return $cmd.Source }
    return $null
}

$adb = Resolve-AdbPath
if (-not $adb) {
    Write-Host "adb not found. Install Android SDK platform-tools or add adb to PATH." -ForegroundColor Red
    exit 1
}

function Get-AdbDevicesText {
    & $adb devices 2>&1 | Out-String
}

function Test-AdbAuthorized {
    $lines = & $adb devices 2>&1 | Where-Object { $_ -match "\tdevice$" }
    return [bool]$lines
}

function Invoke-AdbShell([string]$cmd) {
    & $adb shell $cmd 2>&1
}

function Show-AdbHelp {
    param([string]$DevicesText)
    Write-Host "`nadb devices output:" -ForegroundColor Yellow
    Write-Host $DevicesText
    Write-Host @"

常见原因与处理：
  1. 上次跑脚本已关闭 USB 调试 → 手机上一律手动重新打开：
     设置 → 开发者选项 → USB 调试（+ 无线调试若在用）
  2. 换线 / 换 USB 口，通知栏选「文件传输 / MTP」
  3. 弹「允许 USB 调试？」→ 点允许（可勾始终允许）
  4. PC 执行：adb kill-server && adb start-server && adb devices
  5. 仅抓 log 时不要关调试：.\scripts\maribank-sg-register.ps1 -CaptureLog -KeepAdb

"@ -ForegroundColor Cyan
}

Write-Host "=== MariBank SG Register Test ===" -ForegroundColor Cyan
Write-Host "adb: $adb"

if ($All) {
    $allArgs = @()
    if ($DisableUsbDebug -and -not $KeepAdb) { $allArgs += "-DisableUsbDebug" }
    if ($KeepAdb) { $allArgs += "-KeepAdb" }
    & "$ProjectRoot\scripts\maribank-sg-all-in.ps1" @allArgs
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
    if (-not $CaptureLog) { exit 0 }
}

& $adb start-server 2>&1 | Out-Null
$devicesText = Get-AdbDevicesText

if (-not (Test-AdbAuthorized)) {
    Write-Host "No authorized adb device." -ForegroundColor Red
    Show-AdbHelp -DevicesText $devicesText
    exit 1
}

Write-Host $devicesText

if ($NewIdentity -or $InstallModule) {
    $spoofArgs = @()
    if ($NewIdentity) { $spoofArgs += "-NewIdentity" }
    if ($InstallModule) { $spoofArgs += "-InstallModule" }
    & "$ProjectRoot\scripts\maribank-spoof-device.ps1" @spoofArgs -ClearMariBank
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}

$shouldDisableAdb = $DisableUsbDebug -and -not $KeepAdb
if ($shouldDisableAdb) {
    Write-Host "`n=== Disable USB / wireless debugging (SG stricter) ===" -ForegroundColor Cyan
    Write-Host "WARNING: PC adb will disconnect after this. Re-enable USB debug on phone to connect again." -ForegroundColor Yellow
    Invoke-AdbShell "settings put global adb_enabled 0" | Out-Null
    Invoke-AdbShell "settings put global development_settings_enabled 0" | Out-Null
    Invoke-AdbShell "settings put secure adb_wifi_enabled 0" | Out-Null
    Invoke-AdbShell "su -c 'resetprop init.svc.adbd stopped; resetprop persist.sys.adb_enable 0'" 2>$null | Out-Null
} elseif (-not $KeepAdb) {
    Write-Host "`n=== Skip disabling USB debug (default) ===" -ForegroundColor Cyan
    Write-Host "Use -DisableUsbDebug when ready to test SG without PC adb; use -KeepAdb with -CaptureLog."
}

if (-not $CaptureLog) {
    Write-Host "`n=== Clear SG app + verify IDs ===" -ForegroundColor Cyan
    Invoke-AdbShell "pm clear $Pkg" | Out-Null
    Invoke-AdbShell "su -c 'getprop ro.serialno; settings get secure android_id'"
}

Write-Host ""
Write-Host "=== LSPosed: pick the correct MariBank package ===" -ForegroundColor Yellow
Write-Host "  SG: sg.com.maribankmobile.digitalbank  (v3.2.2, api.maribank.com.sg)"
Write-Host "  PH: ph.seabank.seabank               (v3.22.0, api.seabank.ph)"
Write-Host "  Launch SG: .\scripts\launch-maribank-sg.ps1"
Write-Host ""
Write-Host "Phone: LSPosed -> soft reboot $Pkg"
Write-Host "Then: MariBank SG -> Sign up -> +65 phone -> Next"

if ($CaptureLog -or $DumpLog) {
    if ($CaptureLog) {
        Write-Host ""
        Write-Host "=== logcat cleared; tap Next then press Enter ===" -ForegroundColor Cyan
        & $adb logcat -c
        Write-Host "Tap Next on phone, then press Enter..."
        Read-Host | Out-Null
    } else {
        Write-Host ""
        Write-Host "=== dump current logcat (no clear) ===" -ForegroundColor Cyan
    }
    Write-Host ""
    Write-Host "--- register / dfp / attestation ---" -ForegroundColor Cyan
    $lines = & $adb logcat -d | Select-String "MariBankCapture|MariBankRegister|MariBankEncrypt|MariBankAttest|MariBankDfp|MariBankNative|MariBankRoot HTTP|ProbeGuard|3100012|4067012|OTP_SMS|register summary|dfp/v1|code=0|Gson REGISTRATION|uapi/v2/register|attestation hooks|native-core"
    if ($lines) {
        $lines
    } else {
        Write-Host "(no matches)" -ForegroundColor Yellow
        Write-Host "Likely: Enter pressed before Next, or register API not sent yet."
        Write-Host "You are on phone screen? Tap Next, wait for loading, then run:"
        Write-Host "  .\scripts\maribank-sg-register.ps1 -DumpLog -KeepAdb"
    }
} else {
    Write-Host "`nLog after Next:" -ForegroundColor Cyan
    Write-Host "  .\scripts\maribank-sg-register.ps1 -CaptureLog -KeepAdb"
    Write-Host "  .\scripts\maribank-sg-register.ps1 -DumpLog -KeepAdb   # no clear, dump now"
}

Write-Host ""
Write-Host "Doc: docs/MariBank新加坡突破.md" -ForegroundColor Green
