#!/usr/bin/env pwsh

$env:ANDROID_HOME = "C:\Users\jacob\AppData\Local\Android\Sdk"
$TOOL_PREFIX = "$env:ANDROID_HOME\build-tools\33.0.0"

# Only really works on Windows, for aarch64.

# Create directories
New-Item -ItemType Directory -Force -Path "..\target\apk_build\lib\arm64-v8a"
New-Item -ItemType Directory -Force -Path "..\target\apk_build\res\values"
New-Item -ItemType Directory -Force -Path "..\target\apk_build\res\mipmap-hdpi"
New-Item -ItemType Directory -Force -Path "..\target\apk_build\res\mipmap-mdpi"
New-Item -ItemType Directory -Force -Path "..\target\apk_build\res\mipmap-xhdpi"
New-Item -ItemType Directory -Force -Path "..\target\apk_build\res\mipmap-xxhdpi"

# Copy the shared library
Copy-Item "..\target\aarch64-linux-android\release\libdsa_rs.so" "..\target\apk_build\lib\arm64-v8a\"

# Copy the manifest
Copy-Item "..\resources\emulator\AndroidManifest.xml" "..\target\apk_build\AndroidManifest.xml"

# Copy the icons
Copy-Item "..\resources\emulator\AppIcon.png" "..\target\apk_build\res\mipmap-hdpi\ic_launcher.png"
Copy-Item "..\resources\emulator\AppIcon.png" "..\target\apk_build\res\mipmap-mdpi\ic_launcher.png"
Copy-Item "..\resources\emulator\AppIcon.png" "..\target\apk_build\res\mipmap-xhdpi\ic_launcher.png"
Copy-Item "..\resources\emulator\AppIcon.png" "..\target\apk_build\res\mipmap-xxhdpi\ic_launcher.png"

# Create strings.xml
@"
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">DSA Emulator</string>
</resources>
"@ | Out-File -FilePath "..\target\apk_build\res\values\strings.xml" -Encoding utf8

# Change to build directory
Push-Location "..\target\apk_build"

try {
    # Compile resources
    & "$TOOL_PREFIX\aapt2.exe" compile --dir res -o compiled_resources.zip

    # Link resources
    & "$TOOL_PREFIX\aapt2.exe" link -o unaligned.apk `
        -I "$env:ANDROID_HOME\platforms\android-35\android.jar" `
        --manifest AndroidManifest.xml `
        compiled_resources.zip

    # Add native libraries to APK
    & "C:\Program Files\7-Zip\7z.exe" a -tzip unaligned.apk lib\*

    # Align APK
    & "$TOOL_PREFIX\zipalign.exe" -v 4 unaligned.apk aligned.apk

    # Generate debug keystore if it doesn't exist
    if (-not (Test-Path "debug.keystore")) {
        & keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -keyalg RSA -keysize 2048 -validity 10000 -storepass android -keypass android -dname "CN=Android Debug,O=Android,C=US"
    }

    # Sign APK
    & "$TOOL_PREFIX\apksigner.bat" sign --ks debug.keystore --ks-key-alias androiddebugkey --ks-pass pass:android --key-pass pass:android --out dsa_emulator.apk aligned.apk

    # Copy final APK
    Copy-Item "dsa_emulator.apk" "..\dsa_emulator.apk"

    Write-Host "APK created successfully at: ..\target\dsa_emulator.apk" -ForegroundColor Green
}
catch {
    Write-Error "Build failed: $_"
}
finally {
    # Return to original directory
    Pop-Location
}
