$ErrorActionPreference = "Stop"

$root = Split-Path -Parent $MyInvocation.MyCommand.Path
$outDir = Join-Path $root "build\lua54-luajc-smoke-classes"
$libDir = Join-Path $root "build"
$bcelJar = Join-Path $libDir "bcel-6.12.0.jar"
$commonsJar = Join-Path $libDir "commons-lang3-3.18.0.jar"

function Ensure-Jar {
    param(
        [string]$Path,
        [string]$Url
    )

    if (-not (Test-Path $Path)) {
        New-Item -ItemType Directory -Force (Split-Path -Parent $Path) | Out-Null
        & curl.exe -L $Url -o $Path
        if ($LASTEXITCODE -ne 0) {
            throw "failed to download $Url"
        }
    }
}

Ensure-Jar $bcelJar "https://repo1.maven.org/maven2/org/apache/bcel/bcel/6.12.0/bcel-6.12.0.jar"
Ensure-Jar $commonsJar "https://repo1.maven.org/maven2/org/apache/commons/commons-lang3/3.18.0/commons-lang3-3.18.0.jar"

New-Item -ItemType Directory -Force $outDir | Out-Null

$sources = @(
    "core\src\main\java\org\luaj\vm2\LuaValue.java",
    "core\src\main\java\org\luaj\vm2\LoadState.java",
    "core\src\main\java\org\luaj\vm2\LocVars.java",
    "core\src\main\java\org\luaj\vm2\LuaClosure.java",
    "core\src\main\java\org\luaj\vm2\LuaThread.java",
    "core\src\main\java\org\luaj\vm2\Upvaldesc.java",
    "core\src\main\java\org\luaj\vm2\compiler\DumpState.java",
    "core\src\main\java\org\luaj\vm2\compiler\FuncState.java",
    "core\src\main\java\org\luaj\vm2\compiler\LexState.java",
    "core\src\main\java\org\luaj\vm2\libs\BaseLib.java",
    "core\src\main\java\org\luaj\vm2\libs\CoroutineLib.java",
    "core\src\main\java\org\luaj\vm2\libs\MathLib.java",
    "core\src\main\java\org\luaj\vm2\libs\StringLib.java",
    "jse\src\main\java\org\luaj\vm2\libs\jse\JseMathLib.java",
    "jse\src\main\java\org\luaj\vm2\libs\jse\JsePlatform.java",
    "jse\src\main\java\org\luaj\vm2\luajc\JavaLoader.java",
    "jse\src\main\java\org\luaj\vm2\luajc\LuaJC.java",
    "jse\src\main\java\org\luaj\vm2\luajc\LuaJCDelegateSupport.java",
    "jse\src\main\java\org\luaj\vm2\luajc\LuaJCDelegateFunction.java",
    "jse\src\main\java\org\luaj\vm2\luajc\DelegateJavaGen.java",
    "jse\src\test\java\org\luaj\vm2\Lua54LuaJcSmokeTestMain.java"
)

$classpath = "$bcelJar;$commonsJar;core\src\main\java;jse\src\main\java;jse\src\test\java"
$sourceArgs = $sources | ForEach-Object { Join-Path $root $_ }

& javac -encoding UTF-8 -cp $classpath -d $outDir $sourceArgs
if ($LASTEXITCODE -ne 0) {
    exit $LASTEXITCODE
}

& java -cp "$outDir;$classpath" org.luaj.vm2.Lua54LuaJcSmokeTestMain
exit $LASTEXITCODE
