# build_setup.ps1
# Script to automate creation and building of hMarkdown Installer using Advanced Installer 22.5

$aiPath = "C:\Program Files (x86)\Caphyon\Advanced Installer 22.5\bin\x86\AdvancedInstaller.com"
if (-not (Test-Path $aiPath)) {
    Write-Error "Advanced Installer not found at $aiPath"
    exit 1
}

$projectDir = "E:\ai\C#\hMarkdown"
$aipPath = Join-Path $projectDir "hMarkdown.aip"
$releaseBin = Join-Path $projectDir "hMarkdown\bin\Release\net48"
$exePath = Join-Path $releaseBin "hMarkdown.exe"

# 1. Build the project in Release mode if not built
Write-Host "Building project in Release mode..."
dotnet build -c Release
if ($LASTEXITCODE -ne 0) {
    Write-Error "Failed to build hMarkdown project."
    exit 1
}

# 2. Get product version from executable version
$version = (Get-Item $exePath).VersionInfo.ProductVersion
if ($null -eq $version -or $version -eq "") {
    $version = "1.0.1"
}
# Trim version to standard MSI format (major.minor.build, max 3 parts for Windows Installer product version)
if ($version -match "^\d+\.\d+\.\d+") {
    $version = $Matches[0]
}
Write-Host "Product Version detected: $version"

# 3. Create a new Advanced Installer Project
Write-Host "Creating new Advanced Installer project..."
if (Test-Path $aipPath) {
    Remove-Item $aipPath
}
& $aiPath /newproject $aipPath -type professional -lang tr
if ($LASTEXITCODE -ne 0) {
    Write-Error "Failed to create new Advanced Installer project."
    exit 1
}

# 4. Generate .aic command file
$aicPath = Join-Path $projectDir "setup_commands.aic"
$aicContent = @(
    ";aic",
    "SetVersion $version",
    "SetProperty ProductName=""hMarkdown""",
    "SetProperty Manufacturer=""hOLOlu""",
    "AddFile APPDIR `"$exePath`"",
    "AddFile APPDIR `"$exePath.config`"",
    "AddFile APPDIR `"$exePath.manifest`"",
    "AddFolder APPDIR\icons `"$releaseBin\icons`"",
    "NewShortcut -name `"hMarkdown`" -dir ProgramMenuFolder -target APPDIR\hMarkdown.exe -icon `"$projectDir\hMarkdown.ico`"",
    "NewShortcut -name `"hMarkdown`" -dir DesktopFolder -target APPDIR\hMarkdown.exe -icon `"$projectDir\hMarkdown.ico`"",
    "AddFileAssociation `"hOLOlu.hMarkdown.md`" -desc `"Markdown Document`" -ext md -cmd APPDIR\hMarkdown.exe",
    "Save",
    "Build"
)

# Write command file with ANSI encoding (Windows-1254/UTF-8 signature sometimes confuses command line parsers)
$aicContent | Out-File -FilePath $aicPath -Encoding ascii

# 5. Execute the commands and build
Write-Host "Executing installer setup commands and building..."
& $aiPath /execute $aipPath $aicPath

if ($LASTEXITCODE -eq 0) {
    Write-Host "Installer built successfully!"
    Write-Host "You can find your setup files in the 'hMarkdown-SetupFiles' folder."
} else {
    Write-Error "Failed to build installer."
}

# Cleanup temporary command file
if (Test-Path $aicPath) {
    Remove-Item $aicPath
}
