# Run MariBank register Frida trace on connected device
param(
    [ValidateSet("spawn", "attach")]
    [string]$Mode = "attach",
    [string]$Package = "ph.seabank.seabank"
)

$ErrorActionPreference = "Stop"
$Here = $PSScriptRoot
$LogsDir = Join-Path (Split-Path $Here -Parent) "logs\frida"
New-Item -ItemType Directory -Force -Path $LogsDir | Out-Null
$Script = Join-Path $Here "trace_maribank_register.js"
$LogFile = Join-Path $LogsDir "trace_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"

if (-not (Test-Path $Script)) { throw "missing $Script" }

# adb
$AdbCandidates = @(
    (Join-Path (Split-Path $Here -Parent) "..\platform-tools\adb.exe"),
    "$env:LOCALAPPDATA\Android\Sdk\platform-tools\adb.exe",
    "adb"
)
$Adb = $AdbCandidates | Where-Object { $_ -eq "adb" -or (Test-Path $_) } | Select-Object -First 1
if (-not $Adb) { Write-Warning "adb not in PATH — ensure device connected" }

# frida / python module
$FridaCmd = Get-Command frida -ErrorAction SilentlyContinue
if (-not $FridaCmd) {
    Write-Host "Installing frida-tools..."
    python -m pip install -r (Join-Path $Here "requirements.txt")
}

Write-Host @"

=== MariBank Frida Register Trace ===
Package : $Package
Mode    : $Mode
Script  : $Script
Log     : $LogFile

前置条件 (Pixel 6):
  1. adb devices 能看到设备
  2. 手机已 push 匹配架构的 frida-server 并 root 运行:
       adb push frida-server /data/local/tmp/
       adb shell chmod 755 /data/local/tmp/frida-server
       adb shell su -c '/data/local/tmp/frida-server -D &'
  3. 建议测试时暂时关闭 LSPosed 对本 App 的作用域，避免与 Frida 冲突
  4. 操作: Sign up -> 输入号码 -> Next，观察本窗口输出

"@

$Py312 = "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\python.exe"
$Runner = Join-Path $Here "run_frida_trace.py"
if (Test-Path $Py312) -and (Test-Path $Runner) {
    Write-Host "Using persistent Python runner: $Runner $Mode"
    & $Py312 $Runner $Mode
    exit $LASTEXITCODE
}

$FridaArgs = @("-U", "-f", $Package, "-l", $Script, "-o", $LogFile)
if ($Mode -eq "attach") {
    $FridaArgs = @("-U", $Package, "-l", $Script, "-o", $LogFile)
}

Write-Host "frida $($FridaArgs -join ' ')"
& frida @FridaArgs
