# Define paths
$gitVersionPath = "dotnet-gitversion.exe"
$godotPath = $env:GODOT
$buildDir = ".\build"
$configFile = "export_presets.cfg"
$zipOutputDir = ".\release"
$fileName = "Cirno_No_Reason"

# Step 1: Clear the build directory
if (Test-Path $buildDir) {
    Remove-Item "$buildDir\*" -Recurse -Force
} else {
    New-Item -ItemType Directory -Path $buildDir | Out-Null
}

New-Item -ItemType Directory -Path $buildDir\win | Out-Null
New-Item -ItemType Directory -Path $buildDir\linux | Out-Null

# Step 2: Get version data from GitVersion
$gitVersionOutput = & $gitVersionPath | ConvertFrom-Json
$assemblySemFileVer = $gitVersionOutput.AssemblySemFileVer
$assemblySemVer = $gitVersionOutput.AssemblySemVer
$fullSemVer = $gitVersionOutput.FullSemVer

# Step 3: Set environment variables for use in the build process
[System.Environment]::SetEnvironmentVariable("GIT_ASSEMBLY_SEM_FILE_VER", $assemblySemFileVer, [System.EnvironmentVariableTarget]::Process)
[System.Environment]::SetEnvironmentVariable("GIT_ASSEMBLY_SEM_VER", $assemblySemVer, [System.EnvironmentVariableTarget]::Process)

Write-Host "Set environment variables:"
Write-Host "  GIT_ASSEMBLY_SEM_FILE_VER = $assemblySemFileVer"
Write-Host "  GIT_ASSEMBLY_SEM_VER = $assemblySemVer"

# Step 3: Update export_presets.cfg
if (Test-Path $configFile) {
    (Get-Content $configFile) `
    -replace 'application/file_version="[^"]*"', "application/file_version=`"$assemblySemFileVer`"" `
    -replace 'application/product_version="[^"]*"', "application/product_version=`"$assemblySemVer`"" `
    | Set-Content $configFile
} else {
    Write-Host "Warning: $configFile not found!"
}

# Step 4: Export the build
#& $godotPath --headless --export-release "Windows Desktop" "$buildDir\win\$fileName.exe"

#& $godotPath --headless --export-release "Linux" "$buildDir\linux\$fileName.x86_64"

# Step 4: Export the Windows build via CMD in the same window
$winExportCmd = "`"$godotPath`" --headless --export-release `"Windows Desktop`" `"$buildDir\win\$fileName.exe`""
& cmd.exe /c $winExportCmd

# Step 5: Export the Linux build via CMD in the same window
$linuxExportCmd = "`"$godotPath`" --headless --export-release `"Linux`" `"$buildDir\linux\$fileName.x86_64`""
& cmd.exe /c $linuxExportCmd