#!/usr/bin/env bash
# Patch the generated Android build.gradle.kts with signing + per-arch release builds.
# Run this after `tauri android init` if the gen/android/ directory was regenerated.
set -euo pipefail

BUILD_FILE="src-tauri/gen/android/app/build.gradle.kts"

if [ ! -f "$BUILD_FILE" ]; then
    echo "Error: $BUILD_FILE not found. Run 'tauri android init' first."
    exit 1
fi

if grep -q "keystoreProperties" "$BUILD_FILE" 2>/dev/null; then
    echo "Patch already applied."
    exit 0
fi

# 1. Add keystore properties loading after the tauriProperties block
sed -i '/^val tauriProperties/,/^$/{
  /^$/a\
\
// Release signing config\
val keystorePropertiesFile = java.io.File("/home/msksbr/Android/keystore.properties")\
val keystoreProperties = Properties().apply {\
    if (keystorePropertiesFile.exists()) {\
        keystorePropertiesFile.inputStream().use { load(it) }\
    }\
}
}' "$BUILD_FILE"

# 2. Add signingConfigs block inside the android block, before buildTypes
sed -i '/buildTypes {/i\    signingConfigs {\
        if (keystorePropertiesFile.exists()) {\
            create("release") {\
                storeFile = java.io.File(keystoreProperties["storeFile"] as String)\
                storePassword = keystoreProperties["storePassword"] as String\
                keyAlias = keystoreProperties["keyAlias"] as String\
                keyPassword = keystoreProperties["keyPassword"] as String\
            }\
        }\
    }\
' "$BUILD_FILE"

# 3. Add signingConfig to the release buildType
sed -i '/getByName("release") {/a\            if (keystorePropertiesFile.exists()) {\
                signingConfig = signingConfigs.getByName("release")\
            }' "$BUILD_FILE"

# 4. Add per-arch release APK build task dependency
cat >> "$BUILD_FILE" << 'TASKDEP'

// Also build per-architecture release APKs when universal release is built
tasks.whenTaskAdded {
    if (name == "assembleUniversalRelease") {
        dependsOn("assembleArm64Release", "assembleArmRelease")
    }
}
TASKDEP

echo "Signing config patched into $BUILD_FILE"
