@set "args=%*"
@powershell "iex((@('')*3+(cat '%~f0'|select -skip 3))-join[char]10)"
@exit /b %ERRORLEVEL%

Set-PSDebug -strict
$VerbosePreference = "Continue"

function Do-Copy($src,$dst){
    Write-Verbose ('$ copy "{0}" "{1}"' -f $src,$dst)
    Copy-Item $src $dst
}

function Do-Remove($file){
    Write-Verbose ('$ del "{0}"' -f $file)
    Remove-Item $file
}

Add-Type -Assembly System.Windows.Forms
function Ask-Copy($src,$dst){
    $fname = (Join-Path $dst (Split-Path $src -Leaf))
    if( Test-Path $fname ){
        if( "Yes" -ne [System.Windows.Forms.MessageBox]::Show(
            'Override "{0}" by default ?' -f $fname,
            "NYAGOS Install", "YesNo","Question","button2") ){
            return
        }
    }
    Do-Copy $src $dst
}

function Get-GoArch{
    if( Test-Path "goarch.txt" ){
        Get-Content "goarch.txt"
    }else{
        go version | %{ $_.Split()[-1].Split("/")[-1] }
    }
}

function ForEach-GoDir{
    Get-ChildItem . -Recurse |
    ?{ $_.Extension -eq '.go' } |
    %{ Split-Path $_.FullName -Parent } |
    Sort-Object |
    Get-Unique
}

function Get-Imports {
    Get-ChildItem . -Recurse |
    ?{ $_.Extension -eq '.go' } |
    %{ Get-Content $_.FullName  } |
    %{ ($_ -replace '\s*//.*$','').Split()[-1] <# remove comment #>} |
    ?{ $_ -match 'github.com/' -and -not ($_ -match '/nyagos/') } |
    %{ $_ -replace '"','' } |
    Sort-Object |
    Get-Unique
}

function Go-Fmt{
    Get-ChildItem . -Recurse |
    ?{ $_.Name -like "*.go" -and $_.Mode -like "?a*" } |
    %{
        $fname = $_.FullName
        Write-Verbose -Message "$ go fmt $fname"
        go fmt $fname
        attrib -a $fname
    }
    Get-ChildItem . -Recurse | ?{ $_.Name -eq "syscall.go" } | %{
        $dir = (Split-Path $_.FullName -Parent)
        $dst = (Join-Path $dir "zsyscall.go")
        if( -not (Test-Path $dst) ){
            Write-Verbose -Message ( `
                "Found {0} but not found $dst" `
                -f $_.FullName,$dst )
            pushd $dir
            Write-Verbose -Message ("$ go generate on " + $dir)
            go generate
            popd
        }
    }
}

function Get-Go1stPath {
    if( $env:gopath -ne $null -and $env:gopath -ne "" ){
        $gopath = $env:gopath
    }else{
        $gopath = (Join-Path $env:userprofile "go")
    }
    $gopath.Split(";")[0]
}

function Make-SysO($version) {
    Download-Exe "github.com/josephspurrier/goversioninfo/cmd/goversioninfo" "goversioninfo.exe"
    if( -not ($version -match "^\d+[\._]\d+[\._]\d+[\._]\d+$") ){
        $version = "0.0.0_0"
    }
    $v = $version.Split("[\._]")

    .\goversioninfo.exe `
        "-file-version=$version" `
        "-product-version=$version" `
        "-icon=mains\nyagos.ico" `
        ("-ver-major=" + $v[0]) `
        ("-ver-minor=" + $v[1]) `
        ("-ver-build=" + $v[2]) `
        ("-ver-patch=" + $v[3]) `
        ("-product-ver-major=" + $v[0]) `
        ("-product-ver-minor=" + $v[1]) `
        ("-product-ver-build=" + $v[2]) `
        ("-product-ver-patch=" + $v[3]) `
        "-o" nyagos.syso `
        versioninfo.json
}

function Show-Version($fname) {
    if( Test-Path $fname ){
        Write-Output $fname
        $v = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($fname)
        if( $v ){
            Write-Output ("  FileVersion:    `"{0}`" ({1},{2},{3},{4})" -f
                $v.FileVersion,
                $v.FileMajorPart,
                $v.FileMinorPart,
                $v.FileBuildPart,
                $v.FilePrivatePart)
            Write-Output ("  ProductVersion: `"{0}`" ({1},{2},{3},{4})" -f
                $v.ProductVersion,
                $v.ProductMajorPart,
                $v.ProductMinorPart,
                $v.ProductBuildPart,
                $v.ProductPrivatePart)
        }
        $data = [System.IO.File]::ReadAllBytes($fname)
        $md5 = New-Object System.Security.Cryptography.MD5CryptoServiceProvider
        $bs = $md5.ComputeHash($data)
        Write-Output ("  md5sum: {0}" -f [System.BitConverter]::ToString($bs).ToLower().Replace("-",""))
    }else{
        Write-Error ("{0} not found" -f $fname)
    }
}

function Download-Exe($url,$exename){
    if( Test-Path $exename ){
        Write-Verbose -Message ("Found {0}" -f $exename)
        return
    }
    Write-Verbose -Message ("{0} not found." -f $exename)
    Write-Verbose -Message ("$ go get " + $url)
    go get $url
    $workdir = (Join-Path (Join-Path (Get-Go1stPath) "src") $url)
    $cwd = (Get-Location)
    Set-Location $workdir
    Write-Verbose -Message ("$ go build {0} on {1}" -f $exename,$workdir)
    go build
    Do-Copy $exename $cwd
    Set-Location $cwd
}

function Newer-Than($folder,$target){
    if( -not (Test-Path $target) ){
        Write-Verbose ("{0} not found." -f $target)
        return $true
    }
    $stamp = (Get-ItemProperty $target).LastWriteTime

    Get-ChildItem $folder -Recurse | %{
        if( $_.LastWriteTime -gt $stamp ){
            Write-Verbose ("{0} is newer than {1}" -f $_.FullName,$target)
            return $true
        }
    }
    return $false
}

function Build($version,$tags) {
    Write-Verbose -Message ("Build as version='{0}' tags='{1}'" -f $version,$tags)
    Go-Fmt

    Make-SysO $version

    if( Newer-Than "nyagos.d" "mains\bindata.go" ){
        Download-Exe "github.com/jteeuwen/go-bindata/go-bindata" "go-bindata.exe"
        Write-Verbose -Message "$ go-bindata.exe"
        .\go-bindata.exe -pkg "mains" -o "mains\bindata.go" "nyagos.d/..."
    }

    $ldflags = (git log -1 --date=short --pretty=format:"-X main.stamp=%ad -X main.commit=%H")
    Write-Verbose -Message "$ go build"
    go build "-o" nyagos.exe -ldflags "$ldflags -X main.version=$version" $tags
}

$args = $env:args -split " "

switch( $args[0] ){
    "" {
        Build (git describe --tags) ""
    }
    "debug" {
        Build "" "-tags=debug"
    }
    "release" {
        Build (Get-Content Misc\version.txt) ""
    }
    "status" {
        Show-Version ".\nyagos.exe"
    }
    "vet" {
    }
    "clean" {
        foreach( $p in @(`
            "nyagos.exe",`
            "nyagos.syso",`
            "version.now",`
            "mains\bindata.go",`
            "goversioninfo.exe",`
            "go-bindata.exe" ) )
        {
            if( Test-Path $p ){
                Write-Verbose -Message ("Remove " + $p)
                Remove-Item $p
            }
        }
        Write-Verbose "Search zsyscall.go"
        Get-ChildItem "." -Recurse |
        ?{ $_.Name -eq "zsyscall.go" } |
        %{
            Write-Verbose -Message ("Remove " + $_.FullName)
            Remove-Item $_.FullName
        }

        ForEach-GoDir | %{
            Write-Verbose -Message ("$ go clean on " + $_)
            pushd $_
            go clean
            popd
        }
    }
    "sweep" {
        Get-ChildItem .  -Recurse |
        ?{ $_.Name -like "*~" -or $_.Name -like "*.bak" } |
        %{ Do-Remove $_.FullName }
    }
    "const" {
        $importconst = (Join-Path (Get-Location).Path "go-importconst.exe")
        if( -not (Test-Path $importconst) ){
            Download-Exe "github.com/zetamatta/go-importconst" `
                         "go-importconst.exe"
        }
        Get-ChildItem . -Recurse |
        ?{ $_.Name -eq "makeconst.cmd" } |
        %{
            $private:savePath = $env:path
            $env:path = (@() + (Get-Location).Path + ($env:path -split ";")) -join ";"
            Write-Verbose ("PATH=" + $env:path)
            pushd (Split-Path $_.FullName -Parent)
            cmd /c ($_.FullName)
            popd
            $env:path = $savePath
        }
    }
    "package" {
        nyagos -e "print(nyagos.version or nyagos.stamp)" |
            %{ $version = ($_ -replace "/","") } # get the last line only.
        $private:zipname = ("nyagos-{0}-{1}.zip" -f $version,(Get-GoArch))
        Write-Verbose ("$ zip -9 " + $zipname + " ....")
        zip -9 $zipname `
            nyagos.exe `
            lua53.dll `
            nyagos.lua `
            .nyagos `
            _nyagos `
            makeicon.cmd `
            nyagos.d\*.lua `
            nyagos.d\catalog\*.lua `
            LICENSE `
            readme_ja.md `
            readme.md `
            Doc\*.md
    }
    "install" {
        $installDir = $args[1]
        if( $installDir -eq $null -or $installDir -eq "" ){
            $installDir = (
                Select-String 'INSTALLDIR=([^\)"]+)' Misc\version.cmd |
                %{ $_.Matches.Groups[1].Value }
            )
            if( $installDir -eq $null -or $installDir -eq "" ){
                Write-Warning -Message "Usage: make.ps1 install INSTALLDIR"
                exit
            }
            if( -not (Test-Path $installDir) ){
                Write-Warning -Message ("{0} not found." -f $installDir)
                exit
            }
            Write-Verbose -Message ("installDir="+$installDir)
        }
        Write-Output ('@set "INSTALLDIR={0}"' -f $installDir) |
            Out-File "Misc\version.cmd" -Encoding Default

        robocopy nyagos.d (Join-Path $installDir "nyagos.d") /E
        Write-Verbose ("ERRORLEVEL=" + $LastExitCode)
        if( $LastExitCode -lt 8 ){
            Remove-Item Variable:LastExitCode
        }
        if( -not (Test-Path (Join-Path $installDir "lua53.dll") ) ){
            Do-Copy lua53.dll $installDir
        }
        Do-Copy nyagos.lua $installDir
        Ask-Copy "_nyagos" $installDir
        try{
            Do-Copy nyagos.exe $installDir
        }catch{
            taskkill /F /im nyagos.exe
            Do-Copy nyagos.exe $installDir
            # [void]([System.Windows.Forms.MessageBox]::Show("Done"))
            timeout /T 3
        }
    }
    "get" {
        Get-Imports | ForEach-Object `
            -Process { $_ } `
            -End { "golang.org/x/sys/windows" } |
            %{ Write-Output $_ ; go get -u $_ }
    }
    "fmt" {
        Go-Fmt
    }
    "check-case" {
        $private:dic = @{}
        $private:regex = [regex]"\w+(\-\w+)?"
        $private:done = @{}
        $private:fname = if( $args[1] -ne $null -and $args[1] -ne "" ){
            $args[1]
        }else{
            "make.ps1"
        }
        Get-Content $fname | %{
            $regex.Matches( $_ ) | %{
                $private:one = $_.Value
                $private:key = $one.ToUpper()
                if( $dic.ContainsKey( $key ) ){
                    $private:other = $dic[$key]
                    if( $other -cne $one ){
                        $private:output = ("{0},{1}" -f $one,$other)
                        if( -not $done.ContainsKey($output) ){
                            Write-Output $output
                            $done[ $output ] = $true
                        }
                    }
                }else{
                    $dic.Add($key,$one)
                }
            }
        }
    }
}
if( Test-Path Variable:LastExitCode ){
    exit $LastExitCode
}

# vim:set ft=ps1:

@set "args=%*"
@powershell "iex((@('')*3+(cat '%~f0'|select -skip 3))-join[char]10)"
@exit /b %ERRORLEVEL%

Set-PSDebug -strict
$VerbosePreference = "Continue"

function Do-Copy($src,$dst){
    Write-Verbose ('$ copy "{0}" "{1}"' -f $src,$dst)
    Copy-Item $src $dst
}

function Do-Remove($file){
    Write-Verbose ('$ del "{0}"' -f $file)
    Remove-Item $file
}

Add-Type -Assembly System.Windows.Forms
function Ask-Copy($src,$dst){
    $fname = (Join-Path $dst (Split-Path $src -Leaf))
    if( Test-Path $fname ){
        if( "Yes" -ne [System.Windows.Forms.MessageBox]::Show(
            'Override "{0}" by default ?' -f $fname,
            "NYAGOS Install", "YesNo","Question","button2") ){
            return
        }
    }
    Do-Copy $src $dst
}

function Get-GoArch{
    if( Test-Path "goarch.txt" ){
        Get-Content "goarch.txt"
    }else{
        go version | %{ $_.Split()[-1].Split("/")[-1] }
    }
}

function ForEach-GoDir{
    Get-ChildItem . -Recurse |
    ?{ $_.Extension -eq '.go' } |
    %{ Split-Path $_.FullName -Parent } |
    Sort-Object |
    Get-Unique
}

function Get-Imports {
    Get-ChildItem . -Recurse |
    ?{ $_.Extension -eq '.go' } |
    %{ Get-Content $_.FullName  } |
    %{ ($_ -replace '\s*//.*$','').Split()[-1] <# remove comment #>} |
    ?{ $_ -match 'github.com/' -and -not ($_ -match '/nyagos/') } |
    %{ $_ -replace '"','' } |
    Sort-Object |
    Get-Unique
}

function Go-Fmt{
    Get-ChildItem . -Recurse |
    ?{ $_.Name -like "*.go" -and $_.Mode -like "?a*" } |
    %{
        $fname = $_.FullName
        Write-Verbose -Message "$ go fmt $fname"
        go fmt $fname
        attrib -a $fname
    }
    Get-ChildItem . -Recurse | ?{ $_.Name -eq "syscall.go" } | %{
        $dir = (Split-Path $_.FullName -Parent)
        $dst = (Join-Path $dir "zsyscall.go")
        if( -not (Test-Path $dst) ){
            Write-Verbose -Message ( `
                "Found {0} but not found $dst" `
                -f $_.FullName,$dst )
            pushd $dir
            Write-Verbose -Message ("$ go generate on " + $dir)
            go generate
            popd
        }
    }
}

function Get-Go1stPath {
    if( $env:gopath -ne $null -and $env:gopath -ne "" ){
        $gopath = $env:gopath
    }else{
        $gopath = (Join-Path $env:userprofile "go")
    }
    $gopath.Split(";")[0]
}

function Make-SysO($version) {
    Download-Exe "github.com/josephspurrier/goversioninfo/cmd/goversioninfo" "goversioninfo.exe"
    if( -not ($version -match "^\d+[\._]\d+[\._]\d+[\._]\d+$") ){
        $version = "0.0.0_0"
    }
    $v = $version.Split("[\._]")

    .\goversioninfo.exe `
        "-file-version=$version" `
        "-product-version=$version" `
        "-icon=mains\nyagos.ico" `
        ("-ver-major=" + $v[0]) `
        ("-ver-minor=" + $v[1]) `
        ("-ver-build=" + $v[2]) `
        ("-ver-patch=" + $v[3]) `
        ("-product-ver-major=" + $v[0]) `
        ("-product-ver-minor=" + $v[1]) `
        ("-product-ver-build=" + $v[2]) `
        ("-product-ver-patch=" + $v[3]) `
        "-o" nyagos.syso `
        versioninfo.json
}

function Show-Version($fname) {
    if( Test-Path $fname ){
        Write-Output $fname
        $v = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($fname)
        if( $v ){
            Write-Output ("  FileVersion:    `"{0}`" ({1},{2},{3},{4})" -f
                $v.FileVersion,
                $v.FileMajorPart,
                $v.FileMinorPart,
                $v.FileBuildPart,
                $v.FilePrivatePart)
            Write-Output ("  ProductVersion: `"{0}`" ({1},{2},{3},{4})" -f
                $v.ProductVersion,
                $v.ProductMajorPart,
                $v.ProductMinorPart,
                $v.ProductBuildPart,
                $v.ProductPrivatePart)
        }
        $data = [System.IO.File]::ReadAllBytes($fname)
        $md5 = New-Object System.Security.Cryptography.MD5CryptoServiceProvider
        $bs = $md5.ComputeHash($data)
        Write-Output ("  md5sum: {0}" -f [System.BitConverter]::ToString($bs).ToLower().Replace("-",""))
    }else{
        Write-Error ("{0} not found" -f $fname)
    }
}

function Download-Exe($url,$exename){
    if( Test-Path $exename ){
        Write-Verbose -Message ("Found {0}" -f $exename)
        return
    }
    Write-Verbose -Message ("{0} not found." -f $exename)
    Write-Verbose -Message ("$ go get " + $url)
    go get $url
    $workdir = (Join-Path (Join-Path (Get-Go1stPath) "src") $url)
    $cwd = (Get-Location)
    Set-Location $workdir
    Write-Verbose -Message ("$ go build {0} on {1}" -f $exename,$workdir)
    go build
    Do-Copy $exename $cwd
    Set-Location $cwd
}

function Newer-Than($folder,$target){
    if( -not (Test-Path $target) ){
        Write-Verbose ("{0} not found." -f $target)
        return $true
    }
    $stamp = (Get-ItemProperty $target).LastWriteTime

    Get-ChildItem $folder -Recurse | %{
        if( $_.LastWriteTime -gt $stamp ){
            Write-Verbose ("{0} is newer than {1}" -f $_.FullName,$target)
            return $true
        }
    }
    return $false
}

function Build($version,$tags) {
    Write-Verbose -Message ("Build as version='{0}' tags='{1}'" -f $version,$tags)
    Go-Fmt

    Make-SysO $version

    if( Newer-Than "nyagos.d" "mains\bindata.go" ){
        Download-Exe "github.com/jteeuwen/go-bindata/go-bindata" "go-bindata.exe"
        Write-Verbose -Message "$ go-bindata.exe"
        .\go-bindata.exe -pkg "mains" -o "mains\bindata.go" "nyagos.d/..."
    }

    $ldflags = (git log -1 --date=short --pretty=format:"-X main.stamp=%ad -X main.commit=%H")
    Write-Verbose -Message "$ go build"
    go build "-o" nyagos.exe -ldflags "$ldflags -X main.version=$version" $tags
}

$args = $env:args -split " "

switch( $args[0] ){
    "" {
        Build (git describe --tags) ""
    }
    "debug" {
        Build "" "-tags=debug"
    }
    "release" {
        Build (Get-Content Misc\version.txt) ""
    }
    "status" {
        Show-Version ".\nyagos.exe"
    }
    "vet" {
    }
    "clean" {
        foreach( $p in @(`
            "nyagos.exe",`
            "nyagos.syso",`
            "version.now",`
            "mains\bindata.go",`
            "goversioninfo.exe",`
            "go-bindata.exe" ) )
        {
            if( Test-Path $p ){
                Write-Verbose -Message ("Remove " + $p)
                Remove-Item $p
            }
        }
        Write-Verbose "Search zsyscall.go"
        Get-ChildItem "." -Recurse |
        ?{ $_.Name -eq "zsyscall.go" } |
        %{
            Write-Verbose -Message ("Remove " + $_.FullName)
            Remove-Item $_.FullName
        }

        ForEach-GoDir | %{
            Write-Verbose -Message ("$ go clean on " + $_)
            pushd $_
            go clean
            popd
        }
    }
    "sweep" {
        Get-ChildItem .  -Recurse |
        ?{ $_.Name -like "*~" -or $_.Name -like "*.bak" } |
        %{ Do-Remove $_.FullName }
    }
    "const" {
        $importconst = (Join-Path (Get-Location).Path "go-importconst.exe")
        Download-Exe "github.com/zetamatta/go-importconst" "go-importconst.exe"
        Get-ChildItem . -Recurse |
        ?{ $_.Name -eq "makeconst.cmd" } |
        %{
            $private:savePath = $env:path
            $env:path = (@() + (Get-Location).Path + ($env:path -split ";")) -join ";"
            Write-Verbose ("(temporary) PATH=" + $env:path)
            $private:cwd = (Split-Path $_.FullName -Parent)
            pushd $cwd
            Write-Verbose ("$ chdir " + $cwd)
            Write-Verbose ("$ " + $_.Name)
            & $_.FullName
            popd
            $env:path = $savePath
        }
    }
    "package" {
        nyagos -e "print(nyagos.version or nyagos.stamp)" |
            %{ $version = ($_ -replace "/","") } # get the last line only.
        $private:zipname = ("nyagos-{0}-{1}.zip" -f $version,(Get-GoArch))
        Write-Verbose ("$ zip -9 " + $zipname + " ....")
        zip -9 $zipname `
            nyagos.exe `
            lua53.dll `
            nyagos.lua `
            .nyagos `
            _nyagos `
            makeicon.cmd `
            nyagos.d\*.lua `
            nyagos.d\catalog\*.lua `
            LICENSE `
            readme_ja.md `
            readme.md `
            Doc\*.md
    }
    "install" {
        $installDir = $args[1]
        if( $installDir -eq $null -or $installDir -eq "" ){
            $installDir = (
                Select-String 'INSTALLDIR=([^\)"]+)' Misc\version.cmd |
                %{ $_.Matches.Groups[1].Value }
            )
            if( $installDir -eq $null -or $installDir -eq "" ){
                Write-Warning -Message "Usage: make.ps1 install INSTALLDIR"
                exit
            }
            if( -not (Test-Path $installDir) ){
                Write-Warning -Message ("{0} not found." -f $installDir)
                exit
            }
            Write-Verbose -Message ("installDir="+$installDir)
        }
        Write-Output ('@set "INSTALLDIR={0}"' -f $installDir) |
            Out-File "Misc\version.cmd" -Encoding Default

        robocopy nyagos.d (Join-Path $installDir "nyagos.d") /E
        Write-Verbose ("ERRORLEVEL=" + $LastExitCode)
        if( $LastExitCode -lt 8 ){
            Remove-Item Variable:LastExitCode
        }
        if( -not (Test-Path (Join-Path $installDir "lua53.dll") ) ){
            Do-Copy lua53.dll $installDir
        }
        Do-Copy nyagos.lua $installDir
        Ask-Copy "_nyagos" $installDir
        try{
            Do-Copy nyagos.exe $installDir
        }catch{
            taskkill /F /im nyagos.exe
            Do-Copy nyagos.exe $installDir
            # [void]([System.Windows.Forms.MessageBox]::Show("Done"))
            timeout /T 3
        }
    }
    "get" {
        Get-Imports | ForEach-Object `
            -Process { $_ } `
            -End { "golang.org/x/sys/windows" } |
            %{ Write-Output $_ ; go get -u $_ }
    }
    "fmt" {
        Go-Fmt
    }
    "check-case" {
        $private:dic = @{}
        $private:regex = [regex]"\w+(\-\w+)?"
        $private:done = @{}
        $private:fname = if( $args[1] -ne $null -and $args[1] -ne "" ){
            $args[1]
        }else{
            "make.ps1"
        }
        Get-Content $fname | %{
            $regex.Matches( $_ ) | %{
                $private:one = $_.Value
                $private:key = $one.ToUpper()
                if( $dic.ContainsKey( $key ) ){
                    $private:other = $dic[$key]
                    if( $other -cne $one ){
                        $private:output = ("{0},{1}" -f $one,$other)
                        if( -not $done.ContainsKey($output) ){
                            Write-Output $output
                            $done[ $output ] = $true
                        }
                    }
                }else{
                    $dic.Add($key,$one)
                }
            }
        }
    }
}
if( Test-Path Variable:LastExitCode ){
    exit $LastExitCode
}

# vim:set ft=ps1:

make const: more message

make const: more message


@echo off

if "%ALIASES%" == "" (
  set ALIASES="%CMDER_ROOT%\config\user_aliases.cmd"
)

setlocal enabledelayedexpansion

if "%~1" == "" echo Use /? for help & echo. & goto :p_show

:: check command usage

rem #region parseargument
goto parseargument

:do_shift
  shift

:parseargument
  set currentarg=%~1

  if /i "%currentarg%" equ "/f" (
    set ALIASES=%~2
    shift
    goto :do_shift
  ) else if /i "%currentarg%" == "/reload" (
    goto :p_reload
  ) else if "%currentarg%" equ "/?" (
    goto :p_help
  ) else if /i "%currentarg%" equ "/d" (
    if "%~2" neq "" (
      if "%~3" equ "" (
        :: /d flag for delete existing alias
        call :p_del %~2
        shift
        goto :eof
      )
    )
  ) else if "%currentarg%" neq "" (
    if "%~2" equ "" (
      :: Show the specified alias
      doskey /macros | %WINDIR%\System32\findstr /b %currentarg%= && exit /b
      echo insufficient parameters.
      goto :p_help
    ) else (
      :: handle quotes within command definition, e.g. quoted long file names
      set _x=%*
    )
  )

echo _x=%_x%

rem #endregion parseargument

if "%ALIASES%" neq "%CMDER_ROOT%\config\user_aliases.cmd" (
  set _x=!_x:/f "%ALIASES%" =!

  if not exist "%ALIASES%" (
    echo ;= @echo off>"%ALIASES%"
    echo ;= rem Call DOSKEY and use this file as the macrofile>>"%ALIASES%"
    echo ;= %%SystemRoot%%\system32\doskey /listsize=1000 /macrofile=%%0%%>>"%ALIASES%"
    echo ;= rem In batch mode, jump to the end of the file>>"%ALIASES%"
    echo ;= goto:eof>>"%ALIASES%"
    echo ;= Add aliases below here>>"%ALIASES%"
  )
)

:: create with multiple parameters
if [%1] == [create] (
  if not [%2] == [] (
    if not [%3] == [] (
      set _x=%1=%2
      :: if command create was submitted
      set alias_name=%~2
      shift
      shift
      echo %*
      set alias_value=%*

      for /f "tokens=1,2,* usebackq" %%G in (`echo %*`) do (
        set alias_name=%%H
        set alias_value=%%I
      )
    )
  )
) else (
  :: validate alias
  echo %_x%
  set x=!_x:%=^^%!
  echo !_x!
  for /f "delims== tokens=1,* usebackq" %%G in (`echo "!_x!"`) do (
    set alias_name=%%G
    set alias_value=%%H
  )

  :: leading quotes added while validating
  set alias_name=!alias_name:~1!

  :: trailing quotes added while validating
  set alias_value=!alias_value:~1,-1!
)

::remove spaces
set _temp=%alias_name: =%

if not ["%_temp%"] == ["%alias_name%"] (
	echo Your alias name can not contain a space
	endlocal
	exit /b
)

:: replace already defined alias
%WINDIR%\System32\findstr /b /v /i "%alias_name%=" "%ALIASES%" >> "%ALIASES%.tmp"
echo %alias_name%=%alias_value% >> "%ALIASES%.tmp" && type "%ALIASES%.tmp" > "%ALIASES%" & @del /f /q "%ALIASES%.tmp"
doskey /macrofile="%ALIASES%"
endlocal
exit /b

:p_del
set del_alias=%~1
%WINDIR%\System32\findstr /b /v /i "%del_alias%=" "%ALIASES%" >> "%ALIASES%.tmp"
type "%ALIASES%".tmp > "%ALIASES%" & @del /f /q "%ALIASES%.tmp"
doskey %del_alias%=
doskey /macrofile="%ALIASES%"
goto:eof

:p_reload
doskey /macrofile="%ALIASES%"
echo Aliases reloaded
exit /b

:p_show
doskey /macros|%WINDIR%\System32\findstr /v /r "^;=" | sort
exit /b

:p_help
echo.Usage:
echo.
echo.	alias [options] [alias=full command]
echo.
echo.Options:
echo.
echo.     /d [alias]     Delete an [alias].
echo.     /f [macrofile] Path to the [macrofile] you want to store the new alias in.
echo.                    Default: %cmder_root%\config\user_aliases.cmd
echo.     /reload        Reload the aliases file.  Can be used with /f argument.
echo.                    Default: %cmder_root%\config\user_aliases.cmd
echo.
echo.	If alias is called with no parameters, it will display the list of existing aliases.
echo.
echo.	In the command, you can use the following notations:
echo.	$* allows the alias to assume all the parameters of the supplied command.
echo.	$1-$9 Allows you to seperate parameter by number, much like %%1 in batch.
echo.	$T is the command seperator, allowing you to string several commands together into one alias.
echo.	For more information, read DOSKEY/?
exit /b

@echo off

if "%ALIASES%" == "" (
  set ALIASES="%CMDER_ROOT%\config\user_aliases.cmd"
)

setlocal enabledelayedexpansion

if "%~1" == "" echo Use /? for help & echo. & goto :p_show

:: check command usage

rem #region parseargument
goto parseargument

:do_shift
  shift

:parseargument
  set currentarg=%~1

  if /i "%currentarg%" equ "/f" (
    set ALIASES=%~2
    shift
    goto :do_shift
  ) else if /i "%currentarg%" == "/reload" (
    goto :p_reload
  ) else if "%currentarg%" equ "/?" (
    goto :p_help
  ) else if /i "%currentarg%" equ "/d" (
    if "%~2" neq "" (
      if "%~3" equ "" (
        :: /d flag for delete existing alias
        call :p_del %~2
        shift
        goto :eof
      )
    )
  ) else if "%currentarg%" neq "" (
    if "%~2" equ "" (
      :: Show the specified alias
      doskey /macros | %WINDIR%\System32\findstr /b %currentarg%= && exit /b
      echo insufficient parameters.
      goto :p_help
    ) else (
      :: handle quotes within command definition, e.g. quoted long file names
      set _x=%*
    )
  )
rem #endregion parseargument

if "%ALIASES%" neq "%CMDER_ROOT%\config\user_aliases.cmd" (
  set _x=!_x:/f "%ALIASES%" =!

  if not exist "%ALIASES%" (
    echo ;= @echo off>"%ALIASES%"
    echo ;= rem Call DOSKEY and use this file as the macrofile>>"%ALIASES%"
    echo ;= %%SystemRoot%%\system32\doskey /listsize=1000 /macrofile=%%0%%>>"%ALIASES%"
    echo ;= rem In batch mode, jump to the end of the file>>"%ALIASES%"
    echo ;= goto:eof>>"%ALIASES%"
    echo ;= Add aliases below here>>"%ALIASES%"
  )
)

:: validate alias
for /f "delims== tokens=1,* usebackq" %%G in (`echo "%_x%"`) do (
  set alias_name=%%G
  set alias_value=%%H
)

:: leading quotes added while validating
set alias_name=%alias_name:~1%

:: trailing quotes added while validating
set alias_value=%alias_value:~0,-1%

::remove spaces
set _temp=%alias_name: =%

if not ["%_temp%"] == ["%alias_name%"] (
	echo Your alias name can not contain a space
	endlocal
	exit /b
)

:: replace already defined alias
%WINDIR%\System32\findstr /b /v /i "%alias_name%=" "%ALIASES%" >> "%ALIASES%.tmp"
echo %alias_name%=%alias_value% >> "%ALIASES%.tmp" && type "%ALIASES%.tmp" > "%ALIASES%" & @del /f /q "%ALIASES%.tmp"
doskey /macrofile="%ALIASES%"
endlocal
exit /b

:p_del
set del_alias=%~1
%WINDIR%\System32\findstr /b /v /i "%del_alias%=" "%ALIASES%" >> "%ALIASES%.tmp"
type "%ALIASES%".tmp > "%ALIASES%" & @del /f /q "%ALIASES%.tmp"
doskey %del_alias%=
doskey /macrofile="%ALIASES%"
goto:eof

:p_reload
doskey /macrofile="%ALIASES%"
echo Aliases reloaded
exit /b

:p_show
doskey /macros|%WINDIR%\System32\findstr /v /r "^;=" | sort
exit /b

:p_help
echo.Usage:
echo.
echo.	alias [options] [alias=full command]
echo.
echo.Options:
echo.
echo.     /d [alias]     Delete an [alias].
echo.     /f [macrofile] Path to the [macrofile] you want to store the new alias in.
echo.                    Default: %cmder_root%\config\user_aliases.cmd
echo.     /reload        Reload the aliases file.  Can be used with /f argument.
echo.                    Default: %cmder_root%\config\user_aliases.cmd
echo.
echo.	If alias is called with no parameters, it will display the list of existing aliases.
echo.
echo.	In the command, you can use the following notations:
echo.	$* allows the alias to assume all the parameters of the supplied command.
echo.	$1-$9 Allows you to seperate parameter by number, much like %%1 in batch.
echo.	$T is the command seperator, allowing you to string several commands together into one alias.
echo.	For more information, read DOSKEY/?
exit /b

revert alias.cmd changes

revert alias.cmd changes


@REM Starts Visual Studio Developer Command Prompt.
@IF DEFINED VisualStudioVersion EXIT /B 0

@REM VS2017 uses vswhere.exe for locating the installation.
FOR /f "usebackq delims=" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -prerelease -latest -property installationPath`) do (
  IF EXIST "%%i\Common7\Tools\VsDevCmd.bat" (CALL "%%i\Common7\Tools\VsDevCmd.bat" && GOTO OkRestoreEcho || GOTO Error)
)

@REM VS2015 uses %VS140COMNTOOLS% for locating the installation.
IF "%VS140COMNTOOLS%" NEQ "" (CALL "%VS140COMNTOOLS%VsDevCmd.bat" x86 && GOTO OkRestoreEcho || GOTO Error)

:Error
@ECHO ERROR: Cannot find Visual Studio.
@EXIT /B 1
:OkRestoreEcho
@ECHO ON
@ECHO %~nx0 SUCCESSFULLY COMPLETED.

@REM Starts Visual Studio Developer Command Prompt.
@IF DEFINED VisualStudioVersion EXIT /B 0

@REM https://developercommunity.visualstudio.com/content/problem/26780/vsdevcmdbat-changes-the-current-working-directory.html
SET "VSCMD_START_DIR=%CD%"

@REM VS2017 uses vswhere.exe for locating the installation.
FOR /f "usebackq delims=" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -prerelease -latest -property installationPath`) do (
  IF EXIST "%%i\Common7\Tools\VsDevCmd.bat" (CALL "%%i\Common7\Tools\VsDevCmd.bat" && GOTO OkRestoreEcho || GOTO Error)
)

@REM VS2015 uses %VS140COMNTOOLS% for locating the installation.
IF "%VS140COMNTOOLS%" NEQ "" (CALL "%VS140COMNTOOLS%VsDevCmd.bat" x86 && GOTO OkRestoreEcho || GOTO Error)

:Error
@ECHO ERROR: Cannot find Visual Studio.
@EXIT /B 1
:OkRestoreEcho
@ECHO ON
@ECHO %~nx0 SUCCESSFULLY COMPLETED.

Build script sometimes ended in a wrong working folder. https://developercommunity.visualstudio.com/content/problem/26780/vsdevcmdbat-changes-the-current-working-directory.html


curl -O https://bootstrap.pypa.io/get-pip.py
python get-pip.py
pip install appJar
pip install paramiko

Update hodl.bat

Update hodl.bat


if not exist "C:\Windows\Temp\7z920-x64.msi" (
	powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://downloads.sourceforge.net/sevenzip/7z920-x64.msi', 'C:\Windows\Temp\7z920-x64.msi')" <NUL
)
msiexec /qb /i C:\Windows\Temp\7z920-x64.msi

if not exist "C:\Windows\Temp\ultradefrag.zip" (
	powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://downloads.sourceforge.net/ultradefrag/ultradefrag-portable-6.0.2.bin.amd64.zip', 'C:\Windows\Temp\ultradefrag.zip')" <NUL
)

if not exist "C:\Windows\Temp\ultradefrag-portable-6.0.2.amd64\udefrag.exe" (
	cmd /c ""C:\Program Files\7-Zip\7z.exe" x C:\Windows\Temp\ultradefrag.zip -oC:\Windows\Temp"
)

if not exist "C:\Windows\Temp\SDelete.zip" (
  powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://download.sysinternals.com/files/SDelete.zip', 'C:\Windows\Temp\SDelete.zip')" <NUL
)

if not exist "C:\Windows\Temp\sdelete.exe" (
	cmd /c ""C:\Program Files\7-Zip\7z.exe" x C:\Windows\Temp\SDelete.zip -oC:\Windows\Temp"
)

msiexec /qb /x C:\Windows\Temp\7z920-x64.msi

cmd /c C:\Windows\Temp\ultradefrag-portable-6.0.2.amd64\udefrag.exe --optimize --repeat C:

cmd /c %SystemRoot%\System32\reg.exe ADD HKCU\Software\Sysinternals\SDelete /v EulaAccepted /t REG_DWORD /d 1 /f
cmd /c C:\Windows\Temp\sdelete.exe -q -z C:

make sure we have 7zip in compact.bat

make sure we have 7zip in compact.bat


@echo off

setLocal EnableExtensions EnableDelayedExpansion

set LEIN_VERSION=2.2.0

if "%LEIN_VERSION:~-9%" == "-SNAPSHOT" (
    set SNAPSHOT=YES
) else (
    set SNAPSHOT=NO
)

set ORIGINAL_PWD=%CD%
:: If ORIGINAL_PWD ends with a backslash (such as C:\),
:: we need to escape it with a second backslash.
if "%ORIGINAL_PWD:~-1%x" == "\x" set "ORIGINAL_PWD=%ORIGINAL_PWD%\"

call :FIND_DIR_CONTAINING_UPWARDS project.clj
if "%DIR_CONTAINING%" neq "" cd "%DIR_CONTAINING%"

:: LEIN_JAR and LEIN_HOME variables can be set manually.

if "x%LEIN_HOME%" == "x" (
    set LEIN_HOME=%USERPROFILE%\.lein
)

if "x%LEIN_JAR%" == "x" set LEIN_JAR=!LEIN_HOME!\self-installs\leiningen-!LEIN_VERSION!-standalone.jar

if "%1" == "self-install" goto SELF_INSTALL
if "%1" == "upgrade"      goto UPGRADE

if exist "%~dp0..\src\leiningen\version.clj" (
    :: Running from source checkout.
    call :SET_LEIN_ROOT "%~dp0.."

	set bootstrapfile="!LEIN_ROOT!\leiningen-core\.lein-bootstrap"
	rem in .lein-bootstrap there is only one line where each path is concatenated to each other via a semicolon, there's no semicolon at the end
	rem each path is NOT inside double quotes and may contain spaces (even semicolons but this is not supported here) in their names,
	rem  but they won't/cannot contain double quotes " or colons :  in their names (at least on windows it's not allowed/won't work)

	rem tested when folders contain spaces and when LEIN_ROOT contains semicolon

	if not "x%DEBUG%" == "x" echo LEIN_ROOT=!LEIN_ROOT!

	rem if not "%LEIN_ROOT:;=%" == "%LEIN_ROOT%" (

	rem oddly enough /G:/ should've worked but doesn't where / they say it's console
	rem findstr is C:\Windows\System32\findstr.exe
	echo !LEIN_ROOT! | findstr /C:";" /G:con >nul
	if not errorlevel 1 ( rem aka errorlevel is 0 aka the string ";" was found
		echo Your folder structure !LEIN_ROOT! contains at least one semicolon in its name
		echo This is not allowed and would break things with the generated bootstrap file
		echo Please correct this by renaming the folders to not contain semicolons in their name
		del !bootstrapfile! >nul 2>&1
		echo You'll also have to recreate the bootstrap file just to be sure it has semicolon-free names inside
		echo the bootstrap file^(which was just deleted^) is: !bootstrapfile!
		echo  and the info on how to do that is:
		goto :RUN_BOOTSTRAP
	)

	if not exist !bootstrapfile! goto NO_DEPENDENCIES

	findstr /C:^"\^"^" !bootstrapfile! >nul
	if not errorlevel 1 (
		set hasAtLeastOneDoubleQuote=1
	) ELSE (
		set hasAtLeastOneDoubleQuote=0
	)

	if !hasAtLeastOneDoubleQuote! == 1 (
		echo double quotes detected inside file: !bootstrapfile!
		echo this should not be happening
		goto :RUN_BOOTSTRAP
	)

rem will proceed to set LEIN_LIBS and surround each path from bootstrap file in double quotes and separate it from others with a semicolon
rem the paths inside the bootstrap file do not already contain double quotes but may contain spaces
	rem note worthy: the following won't work due to a hard 1022bytes limit truncation in the variable that was set
	rem set /p LEIN_LIBS=<!bootstrapfile!
	rem so this will work instead:
	rem for /f "usebackq delims=" %%j in (!bootstrapfile!) do set LEIN_LIBS=%%j
	rem just  set LEIN_LIBS="%%j"  is uglier/hacky but would also work here instead of the below:
	for /f "usebackq delims=" %%j in (!bootstrapfile!) do (
		set tmpline=%%j
		call :processPath
	)

	if not "x%DEBUG%" == "x" echo LEIN_LIBS=!LEIN_LIBS!

    if "x!LEIN_LIBS!" == "x" goto NO_DEPENDENCIES

	rem CLASSPATH must contain each path element double quoted and separated by semicolons ie. "c:\some folder";"c:\some other folder";"c:\semicolons;;;;in;name;work okay"
	rem (no end semicolon required)
    set CLASSPATH=!LEIN_LIBS!;"!LEIN_ROOT!\src";"!LEIN_ROOT!\resources"

    :: Apply context specific CLASSPATH entries
    if exist "%~dp0..\.lein-classpath" (
        for /f %%i in ("%~dp0...lein-classpath") do set CONTEXT_CP=%%i

        if NOT "x!CONTEXT_CP!"=="x" (
            set CLASSPATH=!CONTEXT_CP!;!CLASSPATH!
        )
    )

) else (
    :: Not running from a checkout.
    if not exist "%LEIN_JAR%" goto NO_LEIN_JAR
    set CLASSPATH=%LEIN_JAR%

    if exist ".lein-classpath" (
        for /f %%i in (.lein-classpath) do set CONTEXT_CP=%%i

        if NOT "x!CONTEXT_CP!"=="x" (
            set CLASSPATH=!CONTEXT_CP!;!CLASSPATH!
        )
    )
)

if not "x%DEBUG%" == "x" echo CLASSPATH=!CLASSPATH!
:: ##################################################

if "x!JAVA_CMD!" == "x" set JAVA_CMD=java
if "x!LEIN_JAVA_CMD!" == "x" set LEIN_JAVA_CMD=%JAVA_CMD%

rem remove quotes from around java commands
for /f "usebackq delims=" %%i in ('!JAVA_CMD!') do set JAVA_CMD=%%~i
for /f "usebackq delims=" %%i in ('!LEIN_JAVA_CMD!') do set LEIN_JAVA_CMD=%%~i

if "x%JVM_OPTS%" == "x" set JVM_OPTS=%JAVA_OPTS%
goto RUN

:DownloadFile
rem parameters: TargetFileName Address
powershell -? >nul 2>&1
if NOT ERRORLEVEL 9009 (
    powershell -Command "& {param($a,$f) (new-object System.Net.WebClient).DownloadFile($a, $f)}" ""%2"" ""%1""
) else (
    wget >nul 2>&1
    if NOT ERRORLEVEL 9009 (
        wget --no-check-certificate -O %1 %2
    ) else (
        curl>nul 2>&1
        if ERRORLEVEL 9009 goto NO_HTTP_CLIENT
        curl --insecure -f -L -o  %1 %2
    )
)

goto EOF

:NO_LEIN_JAR
echo.
echo %LEIN_JAR% can not be found.
echo You can try running "lein self-install"
echo or change LEIN_JAR environment variable
echo or edit lein.bat to set appropriate LEIN_JAR path.
echo.
goto EOF

:NO_DEPENDENCIES
echo.
echo Leiningen is missing its dependencies.
:RUN_BOOTSTRAP
echo Please run "lein bootstrap" in the leiningen-core/ directory
echo with a stable release of Leiningen. See CONTRIBUTING.md for details.
echo.
goto EOF

:SELF_INSTALL
if exist "%LEIN_JAR%" (
    echo %LEIN_JAR% already exists. Delete and retry.
    goto EOF
)

for %%f in ("%LEIN_JAR%") do set LEIN_INSTALL_DIR="%%~dpf"
if not exist %LEIN_INSTALL_DIR% mkdir %LEIN_INSTALL_DIR%

echo Downloading Leiningen now...

set LEIN_JAR_URL=https://leiningen.s3.amazonaws.com/downloads/leiningen-%LEIN_VERSION%-standalone.jar
call :DownloadFile "%LEIN_JAR%.pending" "%LEIN_JAR_URL%"
if ERRORLEVEL 1 (
    del "%LEIN_JAR%.pending" >nul 2>&1
    goto DOWNLOAD_FAILED
)
move /y "%LEIN_JAR%.pending" "%LEIN_JAR%"
goto EOF

:DOWNLOAD_FAILED
echo.
echo Failed to download %LEIN_JAR_URL%
if %SNAPSHOT% == YES echo See README.md for SNAPSHOT build instructions.
echo.
goto EOF

:UPGRADE
set LEIN_BAT=%~dp0%~nx0
echo The script at %LEIN_BAT% will be upgraded to the latest version in series %LEIN_VERSION%.
set /P ANSWER=Do you want to continue (Y/N)?
if /i {%ANSWER%}=={y}   goto YES_UPGRADE
if /i {%ANSWER%}=={yes} goto YES_UPGRADE
echo Aborted.
exit /B 1

:YES_UPGRADE
echo Downloading latest Leiningen batch script...

set LEIN_BAT_URL=https://raw.github.com/technomancy/leiningen/stable/bin/lein.bat
set TEMP_BAT=%~dp0temp-lein-%RANDOM%%RANDOM%.bat
call :DownloadFile "%LEIN_BAT%.pending" "%LEIN_BAT_URL%"
if ERRORLEVEL 1 (
    del "%LEIN_BAT%.pending" >nul 2>&1
    echo Failed to download %LEIN_BAT_URL%
    goto EOF
)
move /y "%LEIN_BAT%.pending" "%TEMP_BAT%"
echo.
echo Upgrading...
set LEIN_JAR=
call "%TEMP_BAT%" self-install
move /y "%TEMP_BAT%" "%LEIN_BAT%" && goto EOF
goto EOF

:NO_HTTP_CLIENT
echo.
echo ERROR: Neither PowerShell, Wget, or Curl could be found.
echo        Make sure at least one of these tools is installed
echo        and is in PATH. You can get them from URLs below:
echo.
echo PowerShell: "http://www.microsoft.com/powershell"
echo Wget:       "http://users.ugent.be/~bpuype/wget/"
echo Curl:       "http://curl.haxx.se/dlwiz/?type=bin&os=Win32&flav=-&ver=2000/XP"
echo.
goto EOF

:SET_LEIN_ROOT
set LEIN_ROOT=%~f1
goto EOF

:: Find directory containing filename supplied in first argument
:: looking in current directory, and looking up the parent
:: chain until we find it, or run out
:: returns result in %DIR_CONTAINING%
:: empty string if we don't find it
:FIND_DIR_CONTAINING_UPWARDS
set DIR_CONTAINING=%CD%
set LAST_DIR=

:LOOK_AGAIN
if "%DIR_CONTAINING%" == "%LAST_DIR%" (
    :: didn't find it
    set DIR_CONTAINING=
    goto EOF
)

if EXIST "%DIR_CONTAINING%\%1" (
    :: found it - use result in DIR_CONTAINING
    goto EOF
)

set LAST_DIR=%DIR_CONTAINING%
call :GET_PARENT_PATH "%DIR_CONTAINING%\.."
set DIR_CONTAINING=%PARENT_PATH%
goto LOOK_AGAIN

:GET_PARENT_PATH
set PARENT_PATH=%~f1
goto EOF

:RUN
:: We need to disable delayed expansion here because the %* variable
:: may contain bangs (as in test!). There may also be special
:: characters inside the TRAMPOLINE_FILE.
setLocal DisableDelayedExpansion

set "TRAMPOLINE_FILE=%TEMP%\lein-trampoline-%RANDOM%.bat"
del "%TRAMPOLINE_FILE%" 2>nul

"%LEIN_JAVA_CMD%" -client %LEIN_JVM_OPTS% ^
 -Dclojure.compile.path="%DIR_CONTAINING%/target/classes" ^
 -Dleiningen.original.pwd="%ORIGINAL_PWD%" ^
 -cp "%CLASSPATH%" clojure.main -m leiningen.core.main %*

if not exist "%TRAMPOLINE_FILE%" goto EOF
call "%TRAMPOLINE_FILE%"
del "%TRAMPOLINE_FILE%"
goto EOF

rem this label must reside here outside of ( ) from the if block, otherwise the ELSE ( ) block is also executed
:processPath
rem will surround each path with double quotes before appending it to LEIN_LIBS
	for /f "tokens=1* delims=;" %%a in ("%tmpline%") do (
		set LEIN_LIBS=!LEIN_LIBS!"%%a";
		set tmpline=%%b
	)
	if not "%tmpline%" == "" goto :processPath
	goto :eof

:EOF

@echo off

setLocal EnableExtensions EnableDelayedExpansion

set LEIN_VERSION=2.3.3

if "%LEIN_VERSION:~-9%" == "-SNAPSHOT" (
    set SNAPSHOT=YES
) else (
    set SNAPSHOT=NO
)

set ORIGINAL_PWD=%CD%
:: If ORIGINAL_PWD ends with a backslash (such as C:\),
:: we need to escape it with a second backslash.
if "%ORIGINAL_PWD:~-1%x" == "\x" set "ORIGINAL_PWD=%ORIGINAL_PWD%\"

call :FIND_DIR_CONTAINING_UPWARDS project.clj
if "%DIR_CONTAINING%" neq "" cd "%DIR_CONTAINING%"

:: LEIN_JAR and LEIN_HOME variables can be set manually.

if "x%LEIN_HOME%" == "x" (
    set LEIN_HOME=!USERPROFILE!\.lein
)

if "x%LEIN_JAR%" == "x" set "LEIN_JAR=!LEIN_HOME!\self-installs\leiningen-!LEIN_VERSION!-standalone.jar"

if "%1" == "self-install" goto SELF_INSTALL
if "%1" == "upgrade"      goto UPGRADE
if "%1" == "downgrade"    goto UPGRADE

if exist "%~dp0..\src\leiningen\version.clj" (
    :: Running from source checkout.
    call :SET_LEIN_ROOT "%~dp0.."

	set bootstrapfile="!LEIN_ROOT!\leiningen-core\.lein-bootstrap"
	rem in .lein-bootstrap there is only one line where each path is concatenated to each other via a semicolon, there's no semicolon at the end
	rem each path is NOT inside double quotes and may contain spaces (even semicolons but this is not supported here) in their names,
	rem  but they won't/cannot contain double quotes " or colons :  in their names (at least on windows it's not allowed/won't work)

	rem tested when folders contain spaces and when LEIN_ROOT contains semicolon

	if not "x%DEBUG%" == "x" echo LEIN_ROOT=!LEIN_ROOT!

	rem if not "%LEIN_ROOT:;=%" == "%LEIN_ROOT%" (

	rem oddly enough /G:/ should've worked but doesn't where / they say it's console
	rem findstr is C:\Windows\System32\findstr.exe
	echo !LEIN_ROOT! | findstr /C:";" /G:con >nul
	if not errorlevel 1 ( rem aka errorlevel is 0 aka the string ";" was found
		echo Your folder structure !LEIN_ROOT! contains at least one semicolon in its name
		echo This is not allowed and would break things with the generated bootstrap file
		echo Please correct this by renaming the folders to not contain semicolons in their name
		del !bootstrapfile! >nul 2>&1
		echo You'll also have to recreate the bootstrap file just to be sure it has semicolon-free names inside
		echo the bootstrap file^(which was just deleted^) is: !bootstrapfile!
		echo  and the info on how to do that is:
		goto :RUN_BOOTSTRAP
	)

	if not exist !bootstrapfile! goto NO_DEPENDENCIES

	findstr /C:^"\^"^" !bootstrapfile! >nul
	if not errorlevel 1 (
		set hasAtLeastOneDoubleQuote=1
	) ELSE (
		set hasAtLeastOneDoubleQuote=0
	)

	if !hasAtLeastOneDoubleQuote! == 1 (
		echo double quotes detected inside file: !bootstrapfile!
		echo this should not be happening
		goto :RUN_BOOTSTRAP
	)

rem will proceed to set LEIN_LIBS and surround each path from bootstrap file in double quotes and separate it from others with a semicolon
rem the paths inside the bootstrap file do not already contain double quotes but may contain spaces
	rem note worthy: the following won't work due to a hard 1022bytes limit truncation in the variable that was set
	rem set /p LEIN_LIBS=<!bootstrapfile!
	rem so this will work instead:
	rem for /f "usebackq delims=" %%j in (!bootstrapfile!) do set LEIN_LIBS=%%j
	rem just  set LEIN_LIBS="%%j"  is uglier/hacky but would also work here instead of the below:
	for /f "usebackq delims=" %%j in (!bootstrapfile!) do (
		set tmpline=%%j
		call :processPath
	)

	if not "x%DEBUG%" == "x" echo LEIN_LIBS=!LEIN_LIBS!

    if "x!LEIN_LIBS!" == "x" goto NO_DEPENDENCIES

	rem CLASSPATH must contain each path element double quoted and separated by semicolons ie. "c:\some folder";"c:\some other folder";"c:\semicolons;;;;in;name;work okay"
	rem (no end semicolon required)
    set CLASSPATH=!LEIN_LIBS!;"!LEIN_ROOT!\src";"!LEIN_ROOT!\resources"

    :: Apply context specific CLASSPATH entries
    if exist "%~dp0..\.lein-classpath" (
        for /f %%i in ("%~dp0...lein-classpath") do set CONTEXT_CP=%%i

        if NOT "x!CONTEXT_CP!"=="x" (
            set CLASSPATH=!CONTEXT_CP!;!CLASSPATH!
        )
    )

) else (
    :: Not running from a checkout.
    if not exist "%LEIN_JAR%" goto NO_LEIN_JAR
    set CLASSPATH=%LEIN_JAR%

    if exist ".lein-classpath" (
        for /f %%i in (.lein-classpath) do set CONTEXT_CP=%%i

        if NOT "x!CONTEXT_CP!"=="x" (
            set CLASSPATH=!CONTEXT_CP!;!CLASSPATH!
        )
    )
)

if not "x%DEBUG%" == "x" echo CLASSPATH=!CLASSPATH!
:: ##################################################

if "x!JAVA_CMD!" == "x" set JAVA_CMD=java
if "x!LEIN_JAVA_CMD!" == "x" set LEIN_JAVA_CMD=%JAVA_CMD%

rem remove quotes from around java commands
for /f "usebackq delims=" %%i in ('!JAVA_CMD!') do set JAVA_CMD=%%~i
for /f "usebackq delims=" %%i in ('!LEIN_JAVA_CMD!') do set LEIN_JAVA_CMD=%%~i

if "x%JVM_OPTS%" == "x" set JVM_OPTS=%JAVA_OPTS%
goto RUN

:DownloadFile
rem parameters: TargetFileName Address
if NOT "x%HTTP_CLIENT%" == "x" (
    %HTTP_CLIENT% %1 %2
    goto EOF
)
wget >nul 2>&1
if NOT ERRORLEVEL 9009 (
    wget --no-check-certificate -O %1 %2
    goto EOF
)
curl >nul 2>&1
if NOT ERRORLEVEL 9009 (
    rem We set CURL_PROXY to a space character below to pose as a no-op argument
    set CURL_PROXY=
    if NOT "x%HTTPS_PROXY%" == "x" set CURL_PROXY="-x %HTTPS_PROXY%"
    curl %CURL_PROXY% --insecure -f -L -o  %1 %2
    goto EOF
)
powershell -? >nul 2>&1
if NOT ERRORLEVEL 9009 (
    powershell -Command "& {param($a,$f) (new-object System.Net.WebClient).DownloadFile($a, $f)}" ""%2"" ""%1""
    goto EOF
)
goto NO_HTTP_CLIENT

:NO_LEIN_JAR
echo.
echo %LEIN_JAR% can not be found.
echo You can try running "lein self-install"
echo or change LEIN_JAR environment variable
echo or edit lein.bat to set appropriate LEIN_JAR path.
echo.
goto EOF

:NO_DEPENDENCIES
echo.
echo Leiningen is missing its dependencies.
:RUN_BOOTSTRAP
echo Please run "lein bootstrap" in the leiningen-core/ directory
echo with a stable release of Leiningen. See CONTRIBUTING.md for details.
echo.
goto EOF

:SELF_INSTALL
if exist "%LEIN_JAR%" (
    echo %LEIN_JAR% already exists. Delete and retry.
    goto EOF
)

for %%f in ("%LEIN_JAR%") do set LEIN_INSTALL_DIR="%%~dpf"
if not exist %LEIN_INSTALL_DIR% mkdir %LEIN_INSTALL_DIR%

echo Downloading Leiningen now...

set LEIN_JAR_URL=https://leiningen.s3.amazonaws.com/downloads/leiningen-%LEIN_VERSION%-standalone.jar
call :DownloadFile "%LEIN_JAR%.pending" "%LEIN_JAR_URL%"
if ERRORLEVEL 1 (
    del "%LEIN_JAR%.pending" >nul 2>&1
    goto DOWNLOAD_FAILED
)
move /y "%LEIN_JAR%.pending" "%LEIN_JAR%"
goto EOF

:DOWNLOAD_FAILED
echo.
echo Failed to download %LEIN_JAR_URL%
if %SNAPSHOT% == YES echo See README.md for SNAPSHOT build instructions.
echo.
goto EOF

:UPGRADE
set LEIN_BAT=%~dp0%~nx0
set TARGET_VERSION=%2
if "x%2" == "x" set TARGET_VERSION=stable
echo The script at %LEIN_BAT% will be upgraded to the latest %TARGET_VERSION% version.
set /P ANSWER=Do you want to continue (Y/N)?
if /i {%ANSWER%}=={y}   goto YES_UPGRADE
if /i {%ANSWER%}=={yes} goto YES_UPGRADE
echo Aborted.
exit /B 1

:YES_UPGRADE
echo Downloading latest Leiningen batch script...

set LEIN_BAT_URL=https://github.com/technomancy/leiningen/raw/%TARGET_VERSION%/bin/lein.bat
set TEMP_BAT=%~dp0temp-lein-%RANDOM%%RANDOM%.bat
call :DownloadFile "%LEIN_BAT%.pending" "%LEIN_BAT_URL%"
if ERRORLEVEL 1 (
    del "%LEIN_BAT%.pending" >nul 2>&1
    echo Failed to download %LEIN_BAT_URL%
    goto EOF
)
move /y "%LEIN_BAT%.pending" "%TEMP_BAT%"
echo.
echo Upgrading...
set LEIN_JAR=
call "%TEMP_BAT%" self-install
move /y "%TEMP_BAT%" "%LEIN_BAT%" && goto EOF
goto EOF

:NO_HTTP_CLIENT
echo.
echo ERROR: Neither PowerShell, Wget, or Curl could be found.
echo        Make sure at least one of these tools is installed
echo        and is in PATH. You can get them from URLs below:
echo.
echo PowerShell: "http://www.microsoft.com/powershell"
echo Wget:       "http://users.ugent.be/~bpuype/wget/"
echo Curl:       "http://curl.haxx.se/dlwiz/?type=bin&os=Win32&flav=-&ver=2000/XP"
echo.
goto EOF

:SET_LEIN_ROOT
set LEIN_ROOT=%~f1
goto EOF

:: Find directory containing filename supplied in first argument
:: looking in current directory, and looking up the parent
:: chain until we find it, or run out
:: returns result in %DIR_CONTAINING%
:: empty string if we don't find it
:FIND_DIR_CONTAINING_UPWARDS
set DIR_CONTAINING=%CD%
set LAST_DIR=

:LOOK_AGAIN
if "%DIR_CONTAINING%" == "%LAST_DIR%" (
    :: didn't find it
    set DIR_CONTAINING=
    goto EOF
)

if EXIST "%DIR_CONTAINING%\%1" (
    :: found it - use result in DIR_CONTAINING
    goto EOF
)

set LAST_DIR=%DIR_CONTAINING%
call :GET_PARENT_PATH "%DIR_CONTAINING%\.."
set DIR_CONTAINING=%PARENT_PATH%
goto LOOK_AGAIN

:GET_PARENT_PATH
set PARENT_PATH=%~f1
goto EOF

:RUN
:: We need to disable delayed expansion here because the %* variable
:: may contain bangs (as in test!). There may also be special
:: characters inside the TRAMPOLINE_FILE.
setLocal DisableDelayedExpansion

set "TRAMPOLINE_FILE=%TEMP%\lein-trampoline-%RANDOM%.bat"
del "%TRAMPOLINE_FILE%" 2>nul

"%LEIN_JAVA_CMD%" -client %LEIN_JVM_OPTS% ^
 -Dclojure.compile.path="%DIR_CONTAINING%/target/classes" ^
 -Dleiningen.original.pwd="%ORIGINAL_PWD%" ^
 -cp "%CLASSPATH%" clojure.main -m leiningen.core.main %*

if not exist "%TRAMPOLINE_FILE%" goto EOF
call "%TRAMPOLINE_FILE%"
del "%TRAMPOLINE_FILE%"
goto EOF

rem this label must reside here outside of ( ) from the if block, otherwise the ELSE ( ) block is also executed
:processPath
rem will surround each path with double quotes before appending it to LEIN_LIBS
	for /f "tokens=1* delims=;" %%a in ("%tmpline%") do (
		set LEIN_LIBS=!LEIN_LIBS!"%%a";
		set tmpline=%%b
	)
	if not "%tmpline%" == "" goto :processPath
	goto :eof

:EOF

update lein.bat script

update lein.bat script


echo %1 | "C:\Program Files (x86)\BigFix Enterprise\BES Client\qna" -t -showtypes

Create EvalRelevance.bat

Create EvalRelevance.bat


:: batch script to build a binary egg package for the currently active Python

cd ..
del /q /s build-formast\
mkdir build-formast
cd build-formast
cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -DBUILD_JAVA=OFF ..\formast
nmake
cpack -G ZIP
cd swig\python\package
python setup.py bdist_egg

Add batch script used for creating binary egg packages for Python.


REM Building docker image
if "%1"=="--build" docker build -t opendronemap/webodm_slate .

REM Launching server
docker run -ti --rm -v "%CD%":/webodm/slate -p 4567:4567 --entrypoint bash opendronemap/webodm_slate -c "rm Gemfile.lock && bundle install && bundle exec middleman server --watcher-force-polling"

REM Building docker image
if "%1"=="--build" docker build -t opendronemap/webodm_slate .

REM Launching server
docker run -ti --rm -v "%CD%":/webodm/slate -p 4567:4567 --entrypoint bash opendronemap/webodm_slate -c "bundle install && bundle exec middleman server --watcher-force-polling"

Remove rm command

Remove rm command


@set mesa=C:\Software\Development\projects\mesa
@SET PATH=C:\Software\Development\Git\cmd\;%mesa%\Python\;%mesa%\Py3\;%mesa%\Py3\Scripts\;%mesa%\flexbison\;%mesa%\ninja\;%mesa%\pkgconfig\;%PATH%
@call "%ProgramFiles% (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
@cd %mesa%\mesa
@set buildcmd=%mesa%\Py3\python.exe %mesa%\Py3\Scripts\meson.py . .\build\windows-x86_64
@RD /S /Q %mesa%\mesa\build\windows-x86_64
@cmd

Add a debug, highly crude script to start a Mesa3D Meson build

Related #7


REM Add other things if could be automated, RUN THIS AS ADMIN
@echo off
REM Windows Defender scan
cd C:\Program Files\Windows Defender\
MpCmdRun.exe -Scan 2
REM Listing possible penetrations
echo Staring to output active processes!
wmic process list brief > brief.txt
wmic process list full >fullprocess.txt
wmic startup list full > startuplists.txt

REM Add other things if could be automated, RUN THIS AS ADMIN
@echo off
REM Windows Defender scan
cd C:\Program Files\Windows Defender\
MpCmdRun.exe -Scan 2
REM Listing possible penetrations
echo Staring to output active processes!
wmic process list brief > BriefProcesses.txt
wmic process list full >FullProcesses.txt
wmic startup list full > startupLists.txt

Update IntruderDetection.bat

Update IntruderDetection.bat


@REM ------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements.  See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership.  The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License.  You may obtain a copy of the License at
@REM
@REM   http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied.  See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ------------------------------------------------------------

@echo off
setlocal
goto opts

:usage
echo.
echo Usage: %~nx0 [-f[orce]]
echo.
echo   -f[orce]  : Forces a start attempt when ${PRODUCT} processes are found to be running
exit /B 0

:opts
if "%1" == "" goto postopts

if "%1" == "-f" (
  set force=1
) else if "%1" == "-force" (
  set force=1
) else if "%1" == "-usage" (
  goto :usage
) else if "%1" == "-help" (
  goto :usage
) else if "%1" == "--help" (
  goto :usage
) else if "%1" == "--usage" (
  goto :usage
) else (
  echo ERROR: unknown argument '%1'
  call :usage
  exit /B 1
)
shift
goto opts
:postopts

set DIRNAME=%~dp0

pushd %DIRNAME%\..
set CLUSTERDIR=%cd%
cd %CLUSTERDIR%\..\..
set INSTALLDIR=%cd%
set LOGSDIR=%CLUSTERDIR%\logs

echo CLUSTERDIR=%CLUSTERDIR%
echo INSTALLDIR=%INSTALLDIR%
echo LOGSDIR=%LOGSDIR%
echo.
cd "%CLUSTERDIR%"
if NOT EXIST "%LOGSDIR%" (
  mkdir "%LOGSDIR%"
)
call "%INSTALLDIR%\bin\${HELPER_COMMAND}" get_cluster_state -quiet

IF %ERRORLEVEL% EQU 0 (
  echo ERROR: sample cluster address [localhost:${LISTEN_PORT}] already in use
  goto :ERROR
)
set tempfile=%TEMP%\start-sample-cluster-%random%

wmic process where ^
  "name='java.exe' and CommandLine like '%%org.codehaus.mojo.appassembler.booter.AppassemblerBooter%%' and (CommandLine like '%%app.name=\"%%[cn]c\"%%' or CommandLine like '%%app.name=\"%%ncservice\"%%')" ^
  GET processid > %tempfile% 2> nul

set severity=ERROR
if "%force%" == "1" set severity=WARNING

for /F "skip=1" %%P in ('type %tempfile%') DO set found=1

if "%found%" == "1" (
  if "%force%" == "1" (
    echo %severity%: ${PRODUCT} processes are already running; -f[orce] specified, ignoring
    del %tempfile%
 ) else (
    echo %severity%: ${PRODUCT} processes are already running; aborting"
    echo.
    echo Re-run with -f to ignore, or run stop-sample-cluster.bat -f to forcibly terminate all running ${PRODUCT} processes:
    for /F "skip=1" %%P in ('type %tempfile%') DO @echo     - %%P
    del %tempfile%
    exit /B 1
  )
)

goto :post_timestamp

:timestamp
echo "--------------------------" >> %1
echo "%date% %time%" >> %1
echo "--------------------------" >> %1
exit /B 0

:post_timestamp
echo Starting sample cluster...

call :timestamp "%LOGSDIR%\blue-service.log"
call :timestamp "%LOGSDIR%\red-service.log"
call :timestamp "%LOGSDIR%\cc.log"

start /MIN "blue-nc" cmd /c "echo See output in %LOGSDIR%\blue-service.log && "%INSTALLDIR%\bin\${NC_SERVICE_COMMAND}" -logdir - -config-file "%CLUSTERDIR%\conf\blue.conf" >> "%LOGSDIR%\blue-service.log" 2>&1"
start /MIN "red-nc" cmd /c "echo See output in %LOGSDIR%\red-service.log && "%INSTALLDIR%\bin\${NC_SERVICE_COMMAND}" -logdir - >> "%LOGSDIR%\red-service.log" 2>&1"
start /MIN "cc" cmd /c "echo See output in %LOGSDIR%\cc.log && "%INSTALLDIR%\bin\${CC_COMMAND}" -config-file "%CLUSTERDIR%\conf\cc.conf" >>"%LOGSDIR%\cc.log" 2>&1"

echo.
call "%INSTALLDIR%\bin\${HELPER_COMMAND}" wait_for_cluster -timeout 30
if %ERRORLEVEL% EQU 0 (
  goto :END
)

:ERROR
echo.
popd
endlocal
exit /B 1

:END
echo.
popd
endlocal

@REM ------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements.  See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership.  The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License.  You may obtain a copy of the License at
@REM
@REM   http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied.  See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ------------------------------------------------------------

@echo off
setlocal
goto opts

:usage
echo.
echo Usage: %~nx0 [-f[orce]]
echo.
echo   -f[orce]  : Forces a start attempt when ${PRODUCT} processes are found to be running
exit /B 0

:opts
if "%1" == "" goto postopts

if "%1" == "-f" (
  set force=1
) else if "%1" == "-force" (
  set force=1
) else if "%1" == "-usage" (
  goto :usage
) else if "%1" == "-help" (
  goto :usage
) else if "%1" == "--help" (
  goto :usage
) else if "%1" == "--usage" (
  goto :usage
) else (
  echo ERROR: unknown argument '%1'
  call :usage
  exit /B 1
)
shift
goto opts
:postopts

set DIRNAME=%~dp0

pushd %DIRNAME%\..
set CLUSTERDIR=%cd%
cd %CLUSTERDIR%\..\..
set INSTALLDIR=%cd%
set LOGSDIR=%CLUSTERDIR%\logs

echo CLUSTERDIR=%CLUSTERDIR%
echo INSTALLDIR=%INSTALLDIR%
echo LOGSDIR=%LOGSDIR%
echo.
cd "%CLUSTERDIR%"
if NOT EXIST "%LOGSDIR%" (
  mkdir "%LOGSDIR%"
)
call "%INSTALLDIR%\bin\${HELPER_COMMAND}" get_cluster_state -quiet

IF %ERRORLEVEL% EQU 0 (
  echo ERROR: sample cluster address [localhost:${LISTEN_PORT}] already in use
  goto :ERROR
)
set tempfile=%TEMP%\start-sample-cluster-%random%

wmic process where ^
  "name='java.exe' and CommandLine like '%%org.codehaus.mojo.appassembler.booter.AppassemblerBooter%%' and (CommandLine like '%%app.name=\"%%[cn]c\"%%' or CommandLine like '%%app.name=\"%%ncservice\"%%')" ^
  GET processid > %tempfile% 2> nul

set severity=ERROR
if "%force%" == "1" set severity=WARNING

for /F "skip=1" %%P in ('type %tempfile%') DO set found=1

if "%found%" == "1" (
  if "%force%" == "1" (
    echo %severity%: ${PRODUCT} processes are already running; -f[orce] specified, ignoring
    del %tempfile%
 ) else (
    echo %severity%: ${PRODUCT} processes are already running; aborting"
    echo.
    echo Re-run with -f to ignore, or run stop-sample-cluster.bat -f to forcibly terminate all running ${PRODUCT} processes:
    for /F "skip=1" %%P in ('type %tempfile%') DO @echo     - %%P
    del %tempfile%
    exit /B 1
  )
)

goto :post_timestamp

:timestamp
echo -------------------------- >> %1
echo %date% %time% >> %1
echo -------------------------- >> %1
exit /B 0

:post_timestamp
echo Starting sample cluster...

call :timestamp "%LOGSDIR%\blue-service.log"
call :timestamp "%LOGSDIR%\red-service.log"
call :timestamp "%LOGSDIR%\cc.log"

start /MIN "blue-nc" cmd /c "echo See output in %LOGSDIR%\blue-service.log && "%INSTALLDIR%\bin\${NC_SERVICE_COMMAND}" -logdir - -config-file "%CLUSTERDIR%\conf\blue.conf" >> "%LOGSDIR%\blue-service.log" 2>&1"
start /MIN "red-nc" cmd /c "echo See output in %LOGSDIR%\red-service.log && "%INSTALLDIR%\bin\${NC_SERVICE_COMMAND}" -logdir - >> "%LOGSDIR%\red-service.log" 2>&1"
start /MIN "cc" cmd /c "echo See output in %LOGSDIR%\cc.log && "%INSTALLDIR%\bin\${CC_COMMAND}" -config-file "%CLUSTERDIR%\conf\cc.conf" >>"%LOGSDIR%\cc.log" 2>&1"

echo.
call "%INSTALLDIR%\bin\${HELPER_COMMAND}" wait_for_cluster -timeout 30
if %ERRORLEVEL% EQU 0 (
  goto :END
)

:ERROR
echo.
popd
endlocal
exit /B 1

:END
echo.
popd
endlocal

Remove Extraneous Quotes in Start Sample Batchfile

e.g.
"--------------------------"
"Mon 03/20/2017 19:31:01.81"
"--------------------------"

Change-Id: I24581eb36e193628b93cb5be52903beb206c603d
Reviewed-on: https://asterix-gerrit.ics.uci.edu/1605
Sonar-Qube: Jenkins <d95b56ce41a2e1ac4cecdd398defd7414407cc08@fulliautomatix.ics.uci.edu>
Tested-by: Jenkins <d95b56ce41a2e1ac4cecdd398defd7414407cc08@fulliautomatix.ics.uci.edu>
BAD: Jenkins <d95b56ce41a2e1ac4cecdd398defd7414407cc08@fulliautomatix.ics.uci.edu>
Integration-Tests: Jenkins <d95b56ce41a2e1ac4cecdd398defd7414407cc08@fulliautomatix.ics.uci.edu>
Reviewed-by: Ian Maxon <75f98fe183e5455573e3e67a0344be46e7dea75a@apache.org>


@ECHO OFF

REM ===========================================================================
REM Shortcuts for various tasks, emulating UNIX "make".
REM Use this to script for various tasks such as runing tests, install
REM psutil, etc.
REM To run tests run "make.bat test".
REM This script is modeled after my Windows installation so it might
REM need some adjustements in order to work on your system.
REM The following assumptions are made:
REM - Python is installed in C:\PythonXY\python.exe
REM - the right Visual Studio version is installed
REM - in case of Python 2.4 and 2.5 use mingw32 compiler
REM ===========================================================================

SET PYTHON=C:\Python27\python.exe
SET PATH=%PYTHON%;%PATH%
SET PATH=C:\MinGW\bin;%PATH%

if "%1" == "help" (
    :help
    echo Run `make ^<target^>` where ^<target^> is one of:
    echo   clean         clean build files
    echo   build         compile without installing
    echo   install       compile and install
    echo   uninstall     uninstall
    echo   test          run tests
    echo   create-exes   create exe installers in dist directory
    goto :eof
)

if "%1" == "clean" (
    :clean
    for /r %%R in (__pycache__) do if exist %%R (rmdir /S /Q %%R)
    for /r %%R in (*.pyc) do if exist %%R (del /s %%R)
    if exist build (rmdir /S /Q build)
    if exist dist (rmdir /S /Q dist)
    goto :eof
)

if "%1" == "build" (
    :build
    if %PYTHON%==C:\Python24\python.exe (
        %PYTHON% setup.py build -c mingw32
    ) else if %PYTHON%==C:\Python25\python.exe (
        %PYTHON% setup.py build -c mingw32
    ) else (
        %PYTHON% setup.py build
    )
    goto :eof
)

if "%1" == "install" (
    install:
    call :build
    %PYTHON% setup.py install
    goto :eo
)

if "%1" == "uninstall" (
    uninstall:
    rmdir /S /Q %PYTHON%\Lib\site-packages\psutil
    del /F /S /Q %PYTHON%\Lib\site-packages\psutil*
    del /F /S /Q %PYTHON%\Lib\site-packages\_psutil*
    goto :eof
)

if "%1" == "test" (
    test:
    call :install
    %PYTHON% test/test_psutil.py
    goto :eof
)

if "%1" == "create-exes" (
    create-exes:
    call :clean
    C:\Python26\python.exe setup.py build bdist_wininst
    C:\Python27\python.exe setup.py build bdist_wininst
    C:\Python33\python.exe setup.py build bdist_wininst
    goto :eof
)

goto :help

:eof

@ECHO OFF

REM ==========================================================================
REM Shortcuts for various tasks, emulating UNIX "make".
REM Use this to script for various tasks such as runing tests, install
REM psutil, etc.
REM To run tests run "make.bat test".
REM This script is modeled after my Windows installation so it might
REM need some adjustements in order to work on your system.
REM The following assumptions are made:
REM - Python is installed in C:\PythonXY\python.exe
REM - the right Visual Studio version is installed
REM - in case of Python 2.4 and 2.5 use mingw32 compiler
REM ==========================================================================

SET PYTHON=C:\Python27\python.exe
SET PATH=%PYTHON%;%PATH%
SET PATH=C:\MinGW\bin;%PATH%

if "%1" == "help" (
    :help
    echo Run `make ^<target^>` where ^<target^> is one of:
    echo   clean         clean build files
    echo   build         compile without installing
    echo   install       compile and install
    echo   uninstall     uninstall
    echo   test          run tests
    echo   create-exes   create exe installers in dist directory
    goto :eof
)

if "%1" == "clean" (
    :clean
    for /r %%R in (__pycache__) do if exist %%R (rmdir /S /Q %%R)
    for /r %%R in (*.pyc) do if exist %%R (del /s %%R)
    if exist build (rmdir /S /Q build)
    if exist dist (rmdir /S /Q dist)
    goto :eof
)

if "%1" == "build" (
    :build
    if %PYTHON%==C:\Python24\python.exe (
        %PYTHON% setup.py build -c mingw32
    ) else if %PYTHON%==C:\Python25\python.exe (
        %PYTHON% setup.py build -c mingw32
    ) else (
        %PYTHON% setup.py build
    )
    if %errorlevel% neq 0 goto :error
    goto :eof
)

if "%1" == "install" (
    :install
    call :build
    %PYTHON% setup.py install
    goto :eof
)

if "%1" == "uninstall" (
    :uninstall
    rmdir /S /Q %PYTHON%\Lib\site-packages\psutil
    del /F /S /Q %PYTHON%\Lib\site-packages\psutil*
    del /F /S /Q %PYTHON%\Lib\site-packages\_psutil*
    goto :eof
)

if "%1" == "test" (
    :test
    call :install
    %PYTHON% test/test_psutil.py
    goto :eof
)

if "%1" == "create-exes" (
    :create-exes
    call :clean
    C:\Python26\python.exe setup.py build bdist_wininst
    if %errorlevel% neq 0 goto :error
    C:\Python27\python.exe setup.py build bdist_wininst
    if %errorlevel% neq 0 goto :error
    C:\Python33\python.exe setup.py build bdist_wininst
    if %errorlevel% neq 0 goto :error
    goto :eof
)

:error
    echo last command returned an error; exiting
    exit /b %errorlevel%

goto :help

exit on error

make.bat: exit on error


ghc --make -iD:\sources\yhc\h.o\yhc\src\libraries\core -iD:\sources\yhc\h.o\yhc\src\libraries\general -hidir obj -odir obj -o drhaskell.exe Main

mkdir obj 2> nul
ghc --make -iD:\sources\yhc\h.o\yhc\src\libraries\core -hidir obj -odir obj -o drhaskell.exe Main

Fix up the make.bat file

Fix up the make.bat file


@set args=%*
@powershell "iex((@('')*3+(cat '%~f0'|select -skip 3))-join[char]10)"
@exit /b %ERRORLEVEL%

$args = @( ([regex]'"([^"]*)"').Replace($env:args,{
        $args[0].Groups[1] -replace " ",[char]1
    }) -split " " | ForEach-Object{ $_ -replace [char]1," " })

set GO "go.exe" -option constant

set CMD "Cmd" -option constant

Set-PSDebug -strict
$VerbosePreference = "Continue"
$env:GO111MODULE="on"
Write-Verbose -Message "$ set GO111MODULE=$env:GO111MODULE"

function Do-Copy($src,$dst){
    Write-Verbose "$ copy '$src' '$dst'"
    Copy-Item $src $dst
}

function Do-Rename($old,$new){
    Write-Verbose "$ ren $old $new"
    Rename-Item -path $old -newname $new
}

function Do-Remove($file){
    if( Test-Path $file ){
        Write-Verbose "$ del '$file'"
        Remove-Item $file
    }
}

function Make-Dir($folder){
    if( -not (Test-Path $folder) ){
        Write-Verbose "$ mkdir '$folder'"
        New-Item $folder -type directory | Out-Null
    }
}

function Ask-Copy($src,$dst){
    $fname = (Join-Path $dst (Split-Path $src -Leaf))
    if( Test-Path $fname ){
        Write-Verbose "$fname already exists. Cancel to copy"
    }else{
        Do-Copy $src $dst
    }
}

function ForEach-GoDir{
    Get-ChildItem . -Recurse |
    Where-Object{ $_.Extension -eq '.go' } |
    ForEach-Object{ Split-Path $_.FullName -Parent } |
    Sort-Object |
    Get-Unique
}

function Go-Fmt{
    $status = $true
    git status -s | %{
        $fname = $_.Substring(3)
        $arrow = $fname.IndexOf(" -> ")
        if( $arrow -ge 0 ){
            $fname = $fname.Substring($arrow+4)
        }
        if( $fname -like "*.go" -and (Test-Path($fname)) ){
            $prop = Get-ItemProperty($fname)
            if( $prop.Mode -like "?a*" ){
                Write-Verbose "$ $GO fmt $fname"
                & $GO fmt $fname
                if( $LastExitCode -ne 0 ){
                    $status = $false
                }else{
                    attrib -a $fname
                }
            }
        }
    }
    if( -not $status ){
        Write-Warning "Some of '$GO fmt' failed."
    }
    return $status
}

function Make-SysO($version) {
    Download-Exe "github.com/josephspurrier/goversioninfo/cmd/goversioninfo" "goversioninfo.exe"
    if( $version -match "^\d+[\._]\d+[\._]\d+[\._]\d+$" ){
        $v = $version.Split("[\._]")
    }else{
        $v = @(0,0,0,0)
        if( $version -eq $null -or $version -eq "" ){
            $version = "0.0.0_0"
        }
    }
    Write-Verbose "version=$version"

    .\goversioninfo.exe `
        "-file-version=$version" `
        "-product-version=$version" `
        "-icon=nyagos.ico" `
        ("-ver-major=" + $v[0]) `
        ("-ver-minor=" + $v[1]) `
        ("-ver-patch=" + $v[2]) `
        ("-ver-build=" + $v[3]) `
        ("-product-ver-major=" + $v[0]) `
        ("-product-ver-minor=" + $v[1]) `
        ("-product-ver-patch=" + $v[2]) `
        ("-product-ver-build=" + $v[3]) `
        "-o" nyagos.syso `
        versioninfo.json
}

function Download-Exe($url,$exename){
    if( Test-Path $exename ){
        Write-Verbose -Message ("Found {0}" -f $exename)
        return
    }
    Write-Verbose -Message ("{0} not found." -f $exename)
    $private:GO111MODULE = $env:GO111MODULE
    $env:GO111MODULE = "off"
    Write-Verbose -Message ("$ $GO get -d " + $url)
    & $GO get -d $url
    $workdir = (Join-Path (Join-Path (& $GO env GOPATH).Split(";")[0] "src") $url)
    $cwd = (Get-Location)
    Set-Location $workdir
    Write-Verbose -Message ("$ $GO build {0} on {1}" -f $exename,$workdir)
    & $GO build
    Do-Copy $exename $cwd
    Set-Location $cwd
    $env:GO111MODULE = $private:GO111MODULE
}

function Build($version,$tags,[string]$target="") {
    Write-Verbose "Build as version='$version' tags='$tags'"

    if( -not (Go-Fmt) ){
        return
    }
    $saveGOARCH = $env:GOARCH
    $env:GOARCH = (& $go env GOARCH)

    Make-Dir $CMD
    $binDir = (Join-Path $CMD $env:GOARCH)
    Make-Dir $binDir
    if ($target -eq "") {
        $target = (Join-Path $binDir "nyagos.exe")
    }

    Make-SysO $version

    Write-Verbose "$ $GO build -o '$target'"
    & $GO build "-o" $target -ldflags "-s -w -X main.version=$version" $tags
    if( $LastExitCode -eq 0 ){
        Do-Copy $target (Join-Path "." ([System.IO.Path]::GetFileName($target)))
    }
    $env:GOARCH = $saveGOARCH
}

function Make-Package($arch){
    $zipname = ("nyagos-{0}.zip" -f (& cmd\$arch\nyagos.exe --show-version-only))
    Write-Verbose "$ zip -9 $zipname ...."
    if( Test-Path $zipname ){
        Do-Remove $zipname
    }
    zip -9j $zipname `
        "cmd\$arch\nyagos.exe" `
        .nyagos `
        _nyagos `
        makeicon.cmd `
        LICENSE `
        readme_ja.md `
        readme.md

    zip -9 $zipname `
        nyagos.d\*.lua `
        nyagos.d\catalog\*.lua `
        Doc\*.md
}

switch( $args[0] ){
    "" {
        Build (git describe --tags) ""
    }
    "386"{
        $private:save = $env:GOARCH
        $env:GOARCH = "386"
        Build (git describe --tags) ""
        $env:GOARCH = $save
    }
    "debug" {
        $private:save = $env:GOARCH
        if( $args[1] ){
            $env:GOARCH = $args[1]
        }
        Build "" "-tags=debug"
        $env:GOARCH = $save
    }
    "release" {
        $private:save = $env:GOARCH
        if( $args[1] ){
            $env:GOARCH = $args[1]
        }
        Build (Get-Content Etc\version.txt) ""
        $env:GOARCH = $save
    }
    "linux" {
        $private:os = $env:GOOS
        $private:arch = $env:GOARCH
        $env:GOOS="linux"
        $env:GOARCH="amd64"
        Build -target ".\amd64\nyagos" (Get-Content Etc\version.txt) ""
        $env:GOOS = $os
        $env:GOARCH=$arch
    }
    "clean" {
        foreach( $p in @(`
            (Join-Path $CMD "amd64\nyagos.exe"),`
            (Join-Path $CMD "386\nyagos.exe"),`
            "nyagos.exe",`
            "nyagos.syso",`
            "version.now",`
            "goversioninfo.exe") )
        {
            Do-Remove $p
        }
        ForEach-GoDir | %{
            Write-Verbose "$ $GO clean on $_"
            pushd $_
            & $GO clean
            popd
        }
    }
    "package" {
        $goarch = if( $args[1] ){ $args[1] }else{ (& $go env GOARCH) }
        Make-Package $goarch
    }
    "install" {
        $installDir = $args[1]
        if( $installDir -eq $null -or $installDir -eq "" ){
            $installDir = (
                Select-String 'INSTALLDIR=([^\)"]+)' Etc\version.cmd |
                ForEach-Object{ $_.Matches[0].Groups[1].Value }
            )
            if( -not $installDir ){
                Write-Warning "Usage: make.ps1 install INSTALLDIR"
                exit
            }
            if( -not (Test-Path $installDir) ){
                Write-Warning "$installDir not found."
                exit
            }
            Write-Verbose "installDir=$installDir"
        }
        Write-Output "@set `"INSTALLDIR=$installDir`"" |
            Out-File "Etc\version.cmd" -Encoding Default

        robocopy nyagos.d (Join-Path $installDir "nyagos.d") /E
        Write-Verbose ("ERRORLEVEL=" + $LastExitCode)
        if( $LastExitCode -lt 8 ){
            Remove-Item Variable:LastExitCode
        }
        Ask-Copy "_nyagos" $installDir
        try{
            Do-Copy nyagos.exe $installDir
        }catch{
            $now = (Get-Date -Format "yyyyMMddHHmmss")
            try{
                $old = (Join-Path $installDir "nyagos.exe")
                Do-Rename $old ($old + "-" + $now)
                Do-Copy nyagos.exe $installDir
            }catch{
                Write-Host "Could not update installed nyagos.exe"
                Write-Host "Some processes holds nyagos.exe now"
            }
        }
    }
    "get" {
        & $GO get -u
    }
    "fmt" {
        Go-Fmt | Out-Null
    }
    "help" {
        Write-Output @'
make                     build as snapshot
make debug   [386|amd64] build as debug version     (tagged as `debug`)
make release [386|amd64] build as release version
make clean               remove all work files
make package [386|amd64] make `nyagos-(VERSION)-(ARCH).zip`
make install [FOLDER]    copy executables to FOLDER or last folder
make fmt                 `go fmt`
make help                show this
'@
    }
    default {
        Write-Warning ("{0} not supported." -f $args[0])
    }
}
if( Test-Path Variable:LastExitCode ){
    exit $LastExitCode
}

# vim:set ft=ps1:

@set args=%*
@powershell "iex((@('')*3+(cat '%~f0'|select -skip 3))-join[char]10)"
@exit /b %ERRORLEVEL%

$args = @( ([regex]'"([^"]*)"').Replace($env:args,{
        $args[0].Groups[1] -replace " ",[char]1
    }) -split " " | ForEach-Object{ $_ -replace [char]1," " })

set GO "go.exe" -option constant

set CMD "Cmd" -option constant

Set-PSDebug -strict
$VerbosePreference = "Continue"
$env:GO111MODULE="on"
Write-Verbose -Message "$ set GO111MODULE=$env:GO111MODULE"

function Do-Copy($src,$dst){
    Write-Verbose "$ copy '$src' '$dst'"
    Copy-Item $src $dst
}

function Do-Rename($old,$new){
    Write-Verbose "$ ren $old $new"
    Rename-Item -path $old -newname $new
}

function Do-Remove($file){
    if( Test-Path $file ){
        Write-Verbose "$ del '$file'"
        Remove-Item $file
    }
}

function Make-Dir($folder){
    if( -not (Test-Path $folder) ){
        Write-Verbose "$ mkdir '$folder'"
        New-Item $folder -type directory | Out-Null
    }
}

function Ask-Copy($src,$dst){
    $fname = (Join-Path $dst (Split-Path $src -Leaf))
    if( Test-Path $fname ){
        Write-Verbose "$fname already exists. Cancel to copy"
    }else{
        Do-Copy $src $dst
    }
}

function ForEach-GoDir{
    Get-ChildItem . -Recurse |
    Where-Object{ $_.Extension -eq '.go' } |
    ForEach-Object{ Split-Path $_.FullName -Parent } |
    Sort-Object |
    Get-Unique
}

function Go-Fmt{
    $status = $true
    git status -s | %{
        $fname = $_.Substring(3)
        $arrow = $fname.IndexOf(" -> ")
        if( $arrow -ge 0 ){
            $fname = $fname.Substring($arrow+4)
        }
        if( $fname -like "*.go" -and (Test-Path($fname)) ){
            $prop = Get-ItemProperty($fname)
            if( $prop.Mode -like "?a*" ){
                Write-Verbose "$ $GO fmt $fname"
                & $GO fmt $fname
                if( $LastExitCode -ne 0 ){
                    $status = $false
                }else{
                    attrib -a $fname
                }
            }
        }
    }
    if( -not $status ){
        Write-Warning "Some of '$GO fmt' failed."
    }
    return $status
}

function Make-SysO($version) {
    Download-Exe "github.com/josephspurrier/goversioninfo/cmd/goversioninfo" "goversioninfo.exe"
    if( $version -match "^\d+[\._]\d+[\._]\d+[\._]\d+$" ){
        $v = $version.Split("[\._]")
    }else{
        $v = @(0,0,0,0)
        if( $version -eq $null -or $version -eq "" ){
            $version = "0.0.0_0"
        }
    }
    Write-Verbose "version=$version"

    .\goversioninfo.exe `
        "-file-version=$version" `
        "-product-version=$version" `
        "-icon=nyagos.ico" `
        ("-ver-major=" + $v[0]) `
        ("-ver-minor=" + $v[1]) `
        ("-ver-patch=" + $v[2]) `
        ("-ver-build=" + $v[3]) `
        ("-product-ver-major=" + $v[0]) `
        ("-product-ver-minor=" + $v[1]) `
        ("-product-ver-patch=" + $v[2]) `
        ("-product-ver-build=" + $v[3]) `
        "-o" nyagos.syso `
        versioninfo.json
}

function Download-Exe($url,$exename){
    if( Test-Path $exename ){
        Write-Verbose -Message ("Found {0}" -f $exename)
        return
    }
    Write-Verbose -Message ("{0} not found." -f $exename)
    $private:GO111MODULE = $env:GO111MODULE
    $env:GO111MODULE = "off"
    Write-Verbose -Message ("$ $GO get -d " + $url)
    & $GO get -d $url
    $workdir = (Join-Path (Join-Path (& $GO env GOPATH).Split(";")[0] "src") $url)
    $cwd = (Get-Location)
    Set-Location $workdir
    Write-Verbose -Message ("$ $GO build {0} on {1}" -f $exename,$workdir)
    & $GO build
    Do-Copy $exename $cwd
    Set-Location $cwd
    $env:GO111MODULE = $private:GO111MODULE
}

function Build([string]$version="",[string]$tags="",[string]$target="") {
    if( $version -eq "" ){
        $version = (git describe --tags)
    }

    Write-Verbose "Build as version='$version' tags='$tags'"

    if( $tags -ne "" ){
        $tags = "-tags=$tags"
    }

    if( -not (Go-Fmt) ){
        return
    }
    $saveGOARCH = $env:GOARCH
    $env:GOARCH = (& $go env GOARCH)

    Make-Dir $CMD
    $binDir = (Join-Path $CMD $env:GOARCH)
    Make-Dir $binDir
    if ($target -eq "") {
        $target = (Join-Path $binDir "nyagos.exe")
    }

    Make-SysO $version

    Write-Verbose "$ $GO build -o '$target'"
    & $GO build "-o" $target -ldflags "-s -w -X main.version=$version" $tags
    if( $LastExitCode -eq 0 ){
        Do-Copy $target (Join-Path "." ([System.IO.Path]::GetFileName($target)))
    }
    $env:GOARCH = $saveGOARCH
}

function Make-Package($arch){
    $zipname = ("nyagos-{0}.zip" -f (& cmd\$arch\nyagos.exe --show-version-only))
    Write-Verbose "$ zip -9 $zipname ...."
    if( Test-Path $zipname ){
        Do-Remove $zipname
    }
    zip -9j $zipname `
        "cmd\$arch\nyagos.exe" `
        .nyagos `
        _nyagos `
        makeicon.cmd `
        LICENSE `
        readme_ja.md `
        readme.md

    zip -9 $zipname `
        nyagos.d\*.lua `
        nyagos.d\catalog\*.lua `
        Doc\*.md
}

switch( $args[0] ){
    "" {
        Build
    }
    "386"{
        $private:save = $env:GOARCH
        $env:GOARCH = "386"
        Build
        $env:GOARCH = $save
    }
    "debug" {
        $private:save = $env:GOARCH
        if( $args[1] ){
            $env:GOARCH = $args[1]
        }
        Build -tags "debug"
        $env:GOARCH = $save
    }
    "release" {
        $private:save = $env:GOARCH
        if( $args[1] ){
            $env:GOARCH = $args[1]
        }
        Build -version (Get-Content Etc\version.txt)
        $env:GOARCH = $save
    }
    "linux" {
        $private:os = $env:GOOS
        $private:arch = $env:GOARCH
        $env:GOOS="linux"
        $env:GOARCH="amd64"
        Build -target ".\amd64\nyagos" -version (Get-Content Etc\version.txt)
        $env:GOOS = $os
        $env:GOARCH=$arch
    }
    "clean" {
        foreach( $p in @(`
            (Join-Path $CMD "amd64\nyagos.exe"),`
            (Join-Path $CMD "386\nyagos.exe"),`
            "nyagos.exe",`
            "nyagos.syso",`
            "version.now",`
            "goversioninfo.exe") )
        {
            Do-Remove $p
        }
        ForEach-GoDir | %{
            Write-Verbose "$ $GO clean on $_"
            pushd $_
            & $GO clean
            popd
        }
    }
    "package" {
        $goarch = if( $args[1] ){ $args[1] }else{ (& $go env GOARCH) }
        Make-Package $goarch
    }
    "install" {
        $installDir = $args[1]
        if( $installDir -eq $null -or $installDir -eq "" ){
            $installDir = (
                Select-String 'INSTALLDIR=([^\)"]+)' Etc\version.cmd |
                ForEach-Object{ $_.Matches[0].Groups[1].Value }
            )
            if( -not $installDir ){
                Write-Warning "Usage: make.ps1 install INSTALLDIR"
                exit
            }
            if( -not (Test-Path $installDir) ){
                Write-Warning "$installDir not found."
                exit
            }
            Write-Verbose "installDir=$installDir"
        }
        Write-Output "@set `"INSTALLDIR=$installDir`"" |
            Out-File "Etc\version.cmd" -Encoding Default

        robocopy nyagos.d (Join-Path $installDir "nyagos.d") /E
        Write-Verbose ("ERRORLEVEL=" + $LastExitCode)
        if( $LastExitCode -lt 8 ){
            Remove-Item Variable:LastExitCode
        }
        Ask-Copy "_nyagos" $installDir
        try{
            Do-Copy nyagos.exe $installDir
        }catch{
            $now = (Get-Date -Format "yyyyMMddHHmmss")
            try{
                $old = (Join-Path $installDir "nyagos.exe")
                Do-Rename $old ($old + "-" + $now)
                Do-Copy nyagos.exe $installDir
            }catch{
                Write-Host "Could not update installed nyagos.exe"
                Write-Host "Some processes holds nyagos.exe now"
            }
        }
    }
    "get" {
        & $GO get -u
    }
    "fmt" {
        Go-Fmt | Out-Null
    }
    "help" {
        Write-Output @'
make                     build as snapshot
make debug   [386|amd64] build as debug version     (tagged as `debug`)
make release [386|amd64] build as release version
make clean               remove all work files
make package [386|amd64] make `nyagos-(VERSION)-(ARCH).zip`
make install [FOLDER]    copy executables to FOLDER or last folder
make fmt                 `go fmt`
make help                show this
'@
    }
    default {
        Write-Warning ("{0} not supported." -f $args[0])
    }
}
if( Test-Path Variable:LastExitCode ){
    exit $LastExitCode
}

# vim:set ft=ps1:

make.cmd: fix the parameter of the function build()


@echo off
REM -------------------------------------------------------------------------
REM See the NOTICE file distributed with this work for additional
REM information regarding copyright ownership.
REM
REM This is free software; you can redistribute it and/or modify it
REM under the terms of the GNU Lesser General Public License as
REM published by the Free Software Foundation; either version 2.1 of
REM the License, or (at your option) any later version.
REM
REM This software is distributed in the hope that it will be useful,
REM but WITHOUT ANY WARRANTY; without even the implied warranty of
REM MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
REM Lesser General Public License for more details.
REM
REM You should have received a copy of the GNU Lesser General Public
REM License along with this software; if not, write to the Free
REM Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
REM 02110-1301 USA, or see the FSF site: http://www.fsf.org.
REM -------------------------------------------------------------------------

REM -------------------------------------------------------------------------
REM Optional ENV vars
REM -----------------
REM   START_OPTS - parameters passed to the Java VM when running Jetty
REM     e.g. to increase the memory allocated to the JVM to 1GB, use
REM       set START_OPTS=-Xmx1024m
REM -------------------------------------------------------------------------

set JETTY_HOME=jetty
if not defined START_OPTS set START_OPTS=-Xmx512m -XX:MaxPermSize=192m

if not defined JETTY_PORT (
  set JETTY_PORT=%1
  if not defined JETTY_PORT (
    set JETTY_PORT=8080
  )
)

if not defined JETTY_STOP_PORT (
  set JETTY_STOP_PORT=%2
  if not defined JETTY_STOP_PORT (
    set JETTY_STOP_PORT=8079
  )
)

echo Starting Jetty on port %JETTY_PORT% ...

REM Location where XWiki stores generated data and where database files are.
set XWIKI_DATA_DIR=data
set START_OPTS=%START_OPTS% -Dxwiki.data.dir=%XWIKI_DATA_DIR%

REM Ensure the data directory exists so that XWiki can use it for storing permanent data.
if not exist %XWIKI_DATA_DIR% mkdir %XWIKI_DATA_DIR%

REM Ensure the logs directory exists as otherwise Jetty reports an error
if not exist %XWIKI_DATA_DIR%\logs mkdir %XWIKI_DATA_DIR%\logs

REM Ensure the work directory exists so that Jetty uses it for its temporary files.
if not exist %JETTY_HOME%\work mkdir %JETTY_HOME%\work

REM Specify port on which HTTP requests will be handled
set START_OPTS=%START_OPTS% -Djetty.port=%JETTY_PORT%

REM Specify Jetty's home directory
set START_OPTS=%START_OPTS% -Djetty.home=%JETTY_HOME%

REM Specify port and key to stop a running Jetty instance
set START_OPTS=%START_OPTS% -DSTOP.KEY=xwiki -DSTOP.PORT=%JETTY_STOP_PORT%

REM Specify the encoding to use
set START_OPTS=%START_OPTS% -Dfile.encoding=UTF8

REM Path to the solr configuration
set START_OPTS=%START_OPTS% -Dsolr.solr.home=solrconfig

REM In order to avoid getting a "java.lang.IllegalStateException: Form too large" error
REM when editing large page in XWiki we need to tell Jetty to allow for large content
REM since by default it only allows for 20K. We do this by passing the
REM org.eclipse.jetty.server.Request.maxFormContentSize property.
REM Note that setting this value too high can leave your server vulnerable to denial of
REM service attacks.
set START_OPTS=%START_OPTS% -Dorg.eclipse.jetty.server.Request.maxFormContentSize=1000000

java %START_OPTS% %3 %4 %5 %6 %7 %8 %9 -jar %JETTY_HOME%/start.jar

@echo off
REM -------------------------------------------------------------------------
REM See the NOTICE file distributed with this work for additional
REM information regarding copyright ownership.
REM
REM This is free software; you can redistribute it and/or modify it
REM under the terms of the GNU Lesser General Public License as
REM published by the Free Software Foundation; either version 2.1 of
REM the License, or (at your option) any later version.
REM
REM This software is distributed in the hope that it will be useful,
REM but WITHOUT ANY WARRANTY; without even the implied warranty of
REM MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
REM Lesser General Public License for more details.
REM
REM You should have received a copy of the GNU Lesser General Public
REM License along with this software; if not, write to the Free
REM Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
REM 02110-1301 USA, or see the FSF site: http://www.fsf.org.
REM -------------------------------------------------------------------------

REM -------------------------------------------------------------------------
REM Optional ENV vars
REM -----------------
REM   START_OPTS - parameters passed to the Java VM when running Jetty
REM     e.g. to increase the memory allocated to the JVM to 1GB, use
REM       set START_OPTS=-Xmx1024m
REM -------------------------------------------------------------------------

setlocal EnableDelayedExpansion

set JETTY_HOME=jetty
if not defined START_OPTS set START_OPTS=-Xmx512m -XX:MaxPermSize=192m

if not defined JETTY_PORT (
  set JETTY_PORT=%1
  if not defined JETTY_PORT (
    set JETTY_PORT=8080
  )
)

if not defined JETTY_STOP_PORT (
  set JETTY_STOP_PORT=%2
  if not defined JETTY_STOP_PORT (
    set JETTY_STOP_PORT=8079
  )
)

echo Starting Jetty on port %JETTY_PORT% ...

REM Location where XWiki stores generated data and where database files are.
set XWIKI_DATA_DIR=data
set START_OPTS=%START_OPTS% -Dxwiki.data.dir=%XWIKI_DATA_DIR%

REM Ensure the data directory exists so that XWiki can use it for storing permanent data.
if not exist %XWIKI_DATA_DIR% mkdir %XWIKI_DATA_DIR%

REM Ensure the logs directory exists as otherwise Jetty reports an error
if not exist %XWIKI_DATA_DIR%\logs mkdir %XWIKI_DATA_DIR%\logs

REM Ensure the work directory exists so that Jetty uses it for its temporary files.
if not exist %JETTY_HOME%\work mkdir %JETTY_HOME%\work

REM Specify port on which HTTP requests will be handled
set START_OPTS=%START_OPTS% -Djetty.port=%JETTY_PORT%

REM Specify Jetty's home directory
set START_OPTS=%START_OPTS% -Djetty.home=%JETTY_HOME%

REM Specify port and key to stop a running Jetty instance
set START_OPTS=%START_OPTS% -DSTOP.KEY=xwiki -DSTOP.PORT=%JETTY_STOP_PORT%

REM Specify the encoding to use
set START_OPTS=%START_OPTS% -Dfile.encoding=UTF8

REM Path to the solr configuration
set START_OPTS=%START_OPTS% -Dsolr.solr.home=solrconfig

REM In order to avoid getting a "java.lang.IllegalStateException: Form too large" error
REM when editing large page in XWiki we need to tell Jetty to allow for large content
REM since by default it only allows for 20K. We do this by passing the
REM org.eclipse.jetty.server.Request.maxFormContentSize property.
REM Note that setting this value too high can leave your server vulnerable to denial of
REM service attacks.
set START_OPTS=%START_OPTS% -Dorg.eclipse.jetty.server.Request.maxFormContentSize=1000000

set JETTY_CONFIGURATION_FILES=
for /r %%i in (%JETTY_HOME%\etc\jetty-*.xml) do set JETTY_CONFIGURATION_FILES=!JETTY_CONFIGURATION_FILES! "%%i"

java %START_OPTS% %3 %4 %5 %6 %7 %8 %9 -jar %JETTY_HOME%/start.jar %JETTY_HOME%/etc/jetty.xml %JETTY_CONFIGURATION_FILES%

[misc] Split the Jetty configuration into smaller files, to make it easier to configure it
Windows batch file working now.