# Build + install TNG Zygisk exit guard
param(
    [switch]$SkipInstall,
    [switch]$NoReboot
)

$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $PSScriptRoot
$Mod = Join-Path $Root "magisk-modules\tng_exit_guard"
$Ndk = "C:\Users\Administrator\AppData\Local\Android\Sdk\ndk\21.4.7075529"
$NdkBuild = Join-Path $Ndk "ndk-build.cmd"
$Adb = "C:\Users\Administrator\AppData\Local\Android\Sdk\platform-tools\adb.exe"

if (-not (Test-Path $NdkBuild)) {
    throw "ndk-build not found: $NdkBuild"
}

Write-Host "=== ndk-build ===" -ForegroundColor Cyan
Push-Location $Mod
& $NdkBuild NDK_PROJECT_PATH=. APP_BUILD_SCRIPT=jni/Android.mk NDK_APPLICATION_MK=jni/Application.mk -j8
if ($LASTEXITCODE -ne 0) { Pop-Location; throw "ndk-build failed" }

$built = Join-Path $Mod "libs\arm64-v8a\libtng_exit_guard.so"
if (-not (Test-Path $built)) {
    # some ndk versions omit lib prefix based on LOCAL_MODULE
    $built = Get-ChildItem (Join-Path $Mod "libs\arm64-v8a") -Filter "*.so" | Select-Object -First 1 -ExpandProperty FullName
}
if (-not $built -or -not (Test-Path $built)) { Pop-Location; throw "built .so missing" }

$zygiskDir = Join-Path $Mod "zygisk"
New-Item -ItemType Directory -Force -Path $zygiskDir | Out-Null
Copy-Item $built (Join-Path $zygiskDir "arm64-v8a.so") -Force
Write-Host "built -> zygisk\arm64-v8a.so ($((Get-Item (Join-Path $zygiskDir 'arm64-v8a.so')).Length) bytes)"
Pop-Location

if ($SkipInstall) { return }

Write-Host "=== install Magisk module ===" -ForegroundColor Cyan
& $Adb wait-for-device
& $Adb shell "su -c 'mkdir -p /data/adb/modules/tng_exit_guard/zygisk'"
& $Adb push (Join-Path $Mod "module.prop") /data/local/tmp/tng_exit_guard_module.prop
& $Adb push (Join-Path $zygiskDir "arm64-v8a.so") /data/local/tmp/tng_exit_guard.so
& $Adb shell "su -c 'cp /data/local/tmp/tng_exit_guard_module.prop /data/adb/modules/tng_exit_guard/module.prop; cp /data/local/tmp/tng_exit_guard.so /data/adb/modules/tng_exit_guard/zygisk/arm64-v8a.so; chmod 644 /data/adb/modules/tng_exit_guard/module.prop; chmod 755 /data/adb/modules/tng_exit_guard/zygisk/arm64-v8a.so; rm -f /data/adb/modules/tng_exit_guard/disable /data/adb/modules/tng_exit_guard/remove; ls -la /data/adb/modules/tng_exit_guard/ /data/adb/modules/tng_exit_guard/zygisk/'"

if (-not $NoReboot) {
    Write-Host "=== soft reboot zygote (module loads on next specialize) ===" -ForegroundColor Yellow
    Write-Host "Magisk Zygisk modules usually need a FULL reboot. Rebooting device..."
    & $Adb reboot
    Write-Host "Waiting for device..."
    & $Adb wait-for-device
    Start-Sleep -Seconds 25
    & $Adb shell "getprop sys.boot_completed"
}

Write-Host "Done. Launch TNG and check: adb logcat -s TngExitGuard:I LSPosed-Bridge:I" -ForegroundColor Green
