Param(
  [switch]$Release
)

$Compiler = "cl.exe"

$GeneralFlags = "/Wall /WX /wd4996 /wd4464 /wd5105 /std:c11"
$LibraryFlags = "/LD"

$Kernel = (Get-ChildItem Env:OS).Value
$Machine = (Get-ChildItem Env:PROCESSOR_ARCHITECTURE).Value
$Platform = "${Kernel}_${Machine}"

$IncludeDirs = "/I src"
$SrcFiles = "src/wapp.c"

$TestIncludeDirs = Get-ChildItem -Path tests -Recurse -Directory -ErrorAction SilentlyContinue -Force | %{$("/I " + '"' + $_.FullName + '"')}
$TestSrcFiles = Get-ChildItem -Path tests -Recurse -Filter *.c -ErrorAction SilentlyContinue -Force | %{$('"' + $_.FullName + '"')}

If ($Release -eq $True) {
  $GeneralFlags += " /O2 /Og"
  $BuildType = "release"
} Else {
  $GeneralFlags += " /Zi /Od /fsanitize=address"
  $BuildType = "debug"
}

$BuildDir = "./libwapp-build/${Platform}-${BuildType}"
$ObjDir = "$BuildDir/objects"
$OutDir = "$BuildDir/output"
$TestsDir = "$BuildDir/tests"

$OutBasename = "libwapp"
$Objects = "/Fo:$ObjDir/"
$Outputs = "/Fd:$OutDir/$OutBasename /Fe:$OutDir/$OutBasename"

$TestOutBasename = "wapptest"
$TestOutputs = "/Fo:$TestsDir/ /Fe:$TestsDir/$TestOutBasename"

If (Test-Path $BuildDir) {
  Remove-Item $BuildDir -Recurse -Force
}

mkdir -p $ObjDir > $null
mkdir -p $OutDir > $null
mkdir -p $TestsDir > $null

# Run code generation
Invoke-Expression "python -m codegen"

# Build and run tests
Invoke-Expression "$Compiler $GeneralFlags $IncludeDirs $TestIncludeDirs $SrcFiles $TestSrcFiles $TestOutputs" -ErrorAction Stop

Invoke-Expression "$TestsDir/$TestOutBasename.exe"
$Status = $LASTEXITCODE

Remove-Item $TestsDir -Recurse -Force

If ($Status -ne 0) {
  Write-Error "Tests failed"
  Exit 1
}

# Build library
Invoke-Expression "$Compiler $GeneralFlags $LibraryFlags $SrcFiles $Objects $Outputs"
