
<#
.SYNOPSIS
    Builds a Flutter APK with versioning support.

.DESCRIPTION
    This script builds a Flutter APK, manages build numbers, and renames output files.

.PARAMETER buildType
    The build type (release or debug). Default is "release".

.PARAMETER buildName
    The build name (version). Default is "0.0.0".

.EXAMPLE
    .\flutter-build-apk.ps1 -buildType debug -buildName 1.0.0
    Builds a debug APK with version 1.0.0.

.EXAMPLE
    .\flutter-build-apk.ps1 -Help
    Displays this help message.
#>

[CmdletBinding()]
param (
    [string]$buildType = "release",  # Default value is "release"
    [string]$buildName = "0.0.0"    # Default value is "0.0.0"
)

$buildsRef = "builds.json"

# Check if the file exists
if (-not (Test-Path -Path $buildsRef)) {
    # Create the file if it doesn't exist
    New-Item -Path $buildsRef -ItemType File
    $buildsMap = @{
        $buildName = 0
    }
    $buildsMap | ConvertTo-Json | Out-File $buildsRef
    Write-Output "File created: $buildsRef"
} else {
    Write-Output "File already exists: $buildsRef"
}

# Read the JSON file and convert it to a hashtable
$jsonContent = Get-Content $buildsRef -Raw | ConvertFrom-Json
$buildsMap = @{}
$jsonContent.PSObject.Properties | ForEach-Object {
    $buildsMap[$_.Name] = $_.Value
}

if ($buildsMap.ContainsKey($buildName)) {
    Write-Output "Build exists: $buildName"
    $buildNumber = $buildsMap[$buildName]
    $buildNumber++
    Write-Output "Next build number for ${buildName}: $buildNumber"
    $buildsMap[$buildName] = $buildNumber
}
else {
    $buildsMap[$buildName] = 1
}

$buildsMap | ConvertTo-Json | Out-File $buildsRef


$apkDir = "..\build\app\outputs\flutter-apk"
$baseName = "org.igox.apps.android.busylight-buddy"

# Build APK using an array for arguments
$flutterArgs = @(
    "--$buildType",
    "--build-name=$buildName",
    "--build-number=$buildNumber",
    "--target-platform=android-arm,android-arm64,android-x64"
)

Write-Output "Building APK with arguments: $($flutterArgs -join ' ')"

& flutter build apk @flutterArgs

# Rename APK
$oldApk = "$apkDir\app-${buildType}.apk"
$newApk = "$apkDir\$baseName-${buildType}.apk"
if (Test-Path $oldApk) {
    if (Test-Path $newApk) { Remove-Item $newApk -Force }
    Rename-Item -Path $oldApk -NewName "$baseName-${buildType}.apk"
    Write-Host "APK renamed to: $baseName-${buildType}.apk"
}

# Rename SHA1 (if exists)
$oldSha1 = "$apkDir\app-${buildType}.apk.sha1"
$newSha1 = "$apkDir\$baseName-${buildType}.apk.sha1"
if (Test-Path $oldSha1) {
    if (Test-Path $newSha1) { Remove-Item $newSha1 -Force }
    Rename-Item -Path $oldSha1 -NewName "$baseName-${buildType}.apk.sha1"
    Write-Host "SHA1 renamed to: $baseName-${buildType}.apk.sha1"
}