# Install Frida (PC) + frida-server (device) for MariBank trace
param(
    [switch]$SkipServer,
    [switch]$StartServer
)

$ErrorActionPreference = "Stop"
$ProjectRoot = Split-Path -Parent $PSScriptRoot
$FridaDir = Join-Path $ProjectRoot "reverse\frida"
$Req = Join-Path $FridaDir "requirements.txt"
$Sdk = "C:\Users\Administrator\AppData\Local\Android\Sdk"
$Adb = Join-Path $Sdk "platform-tools\adb.exe"

if (-not (Test-Path $Adb)) {
    throw "adb not found: $Adb"
}

# Prefer Python 3.8+ (3.6 breaks frida / type hints)
$Py = $null
foreach ($c in @("py -3.12", "py -3", "python3", "python")) {
    try {
        $v = Invoke-Expression "$c -c `"import sys; print(sys.version_info[:2])`"" 2>$null
        if ($v -match "\(3,\s*([89]|1[0-9])\)") {
            $Py = $c
            break
        }
    } catch {}
}
if (-not $Py) { $Py = "py -3" }

Write-Host "Using Python: $Py" -ForegroundColor Cyan
$env:SSL_CERT_FILE = $null
$env:REQUESTS_CA_BUNDLE = $null
& Invoke-Expression "$Py -m pip install --upgrade pip --trusted-host pypi.org --trusted-host files.pythonhosted.org" 2>&1 | Out-Null
& Invoke-Expression "$Py -m pip install -r `"$Req`" --trusted-host pypi.org --trusted-host files.pythonhosted.org"

$FridaVer = (& Invoke-Expression "$Py -c `"import frida; print(frida.__version__)`"").Trim()
Write-Host "frida-python $FridaVer installed" -ForegroundColor Green

$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "User") + ";" + (
    & Invoke-Expression "$Py -c `"import sysconfig; import os; print(os.path.join(sysconfig.get_path('scripts')))`""
)
$FridaCli = Get-Command frida -ErrorAction SilentlyContinue
if ($FridaCli) {
    Write-Host "frida CLI: $($FridaCli.Source)" -ForegroundColor Green
} else {
    Write-Host "frida CLI not on PATH; use: $Py -m frida" -ForegroundColor Yellow
}

Write-Host "`nadb devices:" -ForegroundColor Cyan
& $Adb devices
$serial = (& $Adb devices | Select-String "device$" | Where-Object { $_ -notmatch "List of" } | ForEach-Object { ($_ -split "\s+")[0] } | Select-Object -First 1)
if (-not $serial) {
    Write-Warning "No device connected — skip frida-server push. Connect Pixel 6 and re-run."
    exit 0
}

if ($SkipServer) { exit 0 }

$Abi = (& $Adb -s $serial shell getprop ro.product.cpu.abi).Trim()
Write-Host "Device ABI: $Abi" -ForegroundColor Cyan

$ArchMap = @{
    "arm64-v8a"   = "android-arm64"
    "armeabi-v7a" = "android-arm"
    "x86_64"      = "android-x86_64"
    "x86"         = "android-x86"
}
if (-not $ArchMap.ContainsKey($Abi)) {
    throw "Unsupported ABI: $Abi"
}
$FridaAsset = $ArchMap[$Abi]
$ServerName = "frida-server-$FridaVer-$FridaAsset"
$ServerDir = Join-Path $FridaDir "bin"
$ServerBin = Join-Path $ServerDir "frida-server"
$XzFile = Join-Path $ServerDir "$ServerName.xz"
New-Item -ItemType Directory -Force -Path $ServerDir | Out-Null

if (-not (Test-Path $ServerBin)) {
    $Url = "https://github.com/frida/frida/releases/download/$FridaVer/$ServerName.xz"
    Write-Host "Downloading $Url ..." -ForegroundColor Cyan
    Invoke-WebRequest -Uri $Url -OutFile $XzFile -UseBasicParsing

    # Windows 10+ tar supports xz in some builds; try 7z or python lzma
    $extracted = $false
    try {
        tar -xf $XzFile -C $ServerDir 2>$null
        if (Test-Path (Join-Path $ServerDir $ServerName)) {
            Move-Item -Force (Join-Path $ServerDir $ServerName) $ServerBin
            $extracted = $true
        }
    } catch {}

    if (-not $extracted) {
        $Py312 = "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\python.exe"
        if (-not (Test-Path $Py312)) { $Py312 = "python" }
        & $Py312 -c @"
import lzma
from pathlib import Path
xz = Path(r'$XzFile')
out = Path(r'$ServerBin')
with lzma.open(xz) as f:
    out.write_bytes(f.read())
print('extracted', out, out.stat().st_size)
"@
        $extracted = Test-Path $ServerBin
    }
    Remove-Item $XzFile -ErrorAction SilentlyContinue
}

if (-not (Test-Path $ServerBin)) {
    throw "frida-server binary missing at $ServerBin"
}

Write-Host "Pushing frida-server to device ..." -ForegroundColor Cyan
& $Adb -s $serial push $ServerBin /data/local/tmp/frida-server
& $Adb -s $serial shell "su -c 'chmod 755 /data/local/tmp/frida-server && pkill -9 frida-server 2>/dev/null; /data/local/tmp/frida-server -D &'" 2>&1 | Out-Null
Start-Sleep -Seconds 2

$check = & $Adb -s $serial shell "su -c 'pgrep frida-server'" 2>&1
if ($check -match "\d") {
    Write-Host "frida-server running (pid $check)" -ForegroundColor Green
} else {
    Write-Warning "frida-server may not be running. Manual: adb shell su -c '/data/local/tmp/frida-server -D &'"
}

if ($StartServer) {
    $Trace = Join-Path $FridaDir "run-frida-trace.ps1"
    Write-Host "Starting trace ..." -ForegroundColor Cyan
    & $Trace -Mode spawn
}

Write-Host @"

安装完成:
  PC  : frida $FridaVer
  手机: /data/local/tmp/frida-server

下一步:
  cd reverse\frida
  ..\..\scripts\install-frida.ps1 -StartServer
  或: frida -U -f ph.seabank.seabank -l trace_maribank_register.js

"@ -ForegroundColor Green
