# One-time / repeatable layout for reverse/ workspace
$ErrorActionPreference = "Stop"
$Reverse = Join-Path (Split-Path -Parent $PSScriptRoot) "reverse"

$dirs = @(
    "scripts", "output", "logs", "logs\frida", "tmp"
)
foreach ($d in $dirs) {
    New-Item -ItemType Directory -Force -Path (Join-Path $Reverse $d) | Out-Null
}

# Python scripts at reverse root -> scripts/
Get-ChildItem (Join-Path $Reverse "*.py") -File -ErrorAction SilentlyContinue | ForEach-Object {
    Move-Item -Force $_.FullName (Join-Path $Reverse "scripts\$($_.Name)")
}

# Dump outputs
@("native_bridge2.txt", "native_bridge_dump.txt", "phone_vm_dump.txt", "crypto_scan.txt") | ForEach-Object {
    $src = Join-Path $Reverse $_
    if (Test-Path $src) { Move-Item -Force $src (Join-Path $Reverse "output\$_") }
}

# Logs
$log = Join-Path $Reverse "maribank_crash.log"
if (Test-Path $log) { Move-Item -Force $log (Join-Path $Reverse "logs\maribank_crash.log") }

$fridaDir = Join-Path $Reverse "frida"
@("*.log", "*.log.err", "logcat_capture.txt", "spawn_runner.out", "trace_runner.out", "trace_runner.err", "spawn_runner.err") | ForEach-Object {
    Get-ChildItem (Join-Path $fridaDir $_) -File -ErrorAction SilentlyContinue | ForEach-Object {
        $dest = Join-Path $Reverse "logs\frida\$($_.Name)"
        try {
            Move-Item -Force $_.FullName $dest -ErrorAction Stop
        } catch {
            Write-Warning "skip locked file: $($_.FullName)"
        }
    }
}

# Temp dex
Get-ChildItem (Join-Path $Reverse "*.dex") -File -ErrorAction SilentlyContinue | ForEach-Object {
    Move-Item -Force $_.FullName (Join-Path $Reverse "tmp\$($_.Name)")
}

# APK archive at root
$zip = Join-Path $Reverse "seabank.zip"
if (Test-Path $zip) { Move-Item -Force $zip (Join-Path $Reverse "apks\seabank.zip") }

# Unpacked APK under extracted/
$apkExtract = Join-Path $Reverse "apk_extract"
if (Test-Path $apkExtract) {
    $dest = Join-Path $Reverse "extracted\apk_extract"
    if (Test-Path $dest) {
        Write-Warning "extracted/apk_extract already exists; leaving reverse/apk_extract in place"
    } else {
        Move-Item -Force $apkExtract $dest
    }
}

Write-Host "reverse/ layout done."
