. ./exiter.ps1

$ErrorActionPreference = "Stop";
trap { $host.SetShouldExit(1) }

$BOSH_INSTALL_TARGET = Resolve-Path "${env:BOSH_INSTALL_TARGET}"

$env:GOROOT="C:\var\vcap\packages\golang-windows\go"
$env:GOPATH="${BOSH_INSTALL_TARGET}"
$env:PATH="${env:GOROOT}\bin;${env:PATH}"

New-Item -ItemType "directory" -Force "${BOSH_INSTALL_TARGET}\src"
robocopy /E . "${BOSH_INSTALL_TARGET}\src\"
if ($LASTEXITCODE -ge 8) {
    Write-Error "robocopy /E . ${BOSH_INSTALL_TARGET}\src\"
}

go.exe build -o ${BOSH_INSTALL_TARGET}\bin\bosh-dns.exe "bosh-dns\dns"
if ($LASTEXITCODE -ne 0) {
    Write-Error "Error compiling: dns"
}

go.exe build -o ${BOSH_INSTALL_TARGET}\bin\bosh-dns-nameserverconfig.exe "bosh-dns\dns\nameserverconfig"
if ($LASTEXITCODE -ne 0) {
    Write-Error "Error compiling: dns\nameserverconfig"
}

go.exe build -o ${BOSH_INSTALL_TARGET}\bin\bosh-dns-health.exe "bosh-dns\healthcheck"
if ($LASTEXITCODE -ne 0) {
    Write-Error "Error compiling: healthcheck"
}

New-Item -ItemType "directory" -Force "emptyfolder"
robocopy /PURGE "emptyfolder" "${BOSH_INSTALL_TARGET}/src"
if ($LASTEXITCODE -ge 8) {
    Write-Error "robocopy /PURGE emptyfolder ${BOSH_INSTALL_TARGET}/src"
}

robocopy /PURGE "emptyfolder" "${BOSH_INSTALL_TARGET}/pkg"
if ($LASTEXITCODE -ge 8) {
    Write-Error "robocopy /PURGE emptyfolder ${BOSH_INSTALL_TARGET}/pkg"
}

robocopy "bosh-dns\dns\nameserverconfig\assets" "${BOSH_INSTALL_TARGET}/bin" "*.ps1"
if ($LASTEXITCODE -ge 8) {
    Write-Error "robocopy bosh-dns\dns\nameserverconfig\assets\*.ps1 ${BOSH_INSTALL_TARGET}/bin"
}

Remove-Item -Force -Recurse "${BOSH_INSTALL_TARGET}/src"
Remove-Item -Force -Recurse "${BOSH_INSTALL_TARGET}/pkg"
Remove-Item -Force -Recurse "emptyfolder"

Exit 0
