param(
    [Parameter(ValueFromRemainingArguments = $true)]
    [string[]]$DotnetArgs
)

$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path

# Keep dotnet and NuGet artifacts local to the repo for easy cleanup.
$env:DOTNET_CLI_HOME = Join-Path $repoRoot ".dotnet_home"
$env:NUGET_PACKAGES = Join-Path $repoRoot ".nuget\packages"
$env:NUGET_HTTP_CACHE_PATH = Join-Path $repoRoot ".nuget\http-cache"

# Keep setup minimal and non-interactive.
$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = "1"
$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH = "0"
$env:DOTNET_GENERATE_ASPNET_CERTIFICATE = "0"
$env:DOTNET_CLI_TELEMETRY_OPTOUT = "1"

# Clear proxy env vars for this process. The host machine currently points them
# to 127.0.0.1:9, which breaks NuGet restore.
Remove-Item Env:HTTP_PROXY -ErrorAction SilentlyContinue
Remove-Item Env:HTTPS_PROXY -ErrorAction SilentlyContinue
Remove-Item Env:ALL_PROXY -ErrorAction SilentlyContinue
Remove-Item Env:http_proxy -ErrorAction SilentlyContinue
Remove-Item Env:https_proxy -ErrorAction SilentlyContinue
Remove-Item Env:all_proxy -ErrorAction SilentlyContinue
Remove-Item Env:GIT_HTTP_PROXY -ErrorAction SilentlyContinue
Remove-Item Env:GIT_HTTPS_PROXY -ErrorAction SilentlyContinue

# Prefer offline cert revocation checks to reduce flaky TLS behavior on constrained hosts.
$env:NUGET_CERT_REVOCATION_MODE = "offline"

New-Item -ItemType Directory -Force -Path $env:DOTNET_CLI_HOME | Out-Null
New-Item -ItemType Directory -Force -Path $env:NUGET_PACKAGES | Out-Null
New-Item -ItemType Directory -Force -Path $env:NUGET_HTTP_CACHE_PATH | Out-Null

if (-not $DotnetArgs -or $DotnetArgs.Count -eq 0) {
    Write-Host "Usage: ./scripts/dotnet-min.ps1 <dotnet args>"
    Write-Host "Example: ./scripts/dotnet-min.ps1 build Journal.Sidecar/Journal.Sidecar.csproj"
    exit 2
}

$firstArg = $DotnetArgs[0].ToLowerInvariant()
$effectiveArgs = @($DotnetArgs)

if ($firstArg -in @("restore", "build", "run", "test", "publish", "pack")) {
    if (-not ($effectiveArgs -contains "-p:RestoreIgnoreFailedSources=true")) {
        $effectiveArgs += "-p:RestoreIgnoreFailedSources=true"
    }
    if (-not ($effectiveArgs -contains "-p:NuGetAudit=false")) {
        $effectiveArgs += "-p:NuGetAudit=false"
    }
}

if ($firstArg -eq "restore") {
    if (-not ($effectiveArgs -contains "--ignore-failed-sources")) {
        $effectiveArgs += "--ignore-failed-sources"
    }
}

& dotnet @effectiveArgs
exit $LASTEXITCODE
