@if "%SCM_TRACE_LEVEL%" NEQ "4" @echo off

:: ----------------------
:: KUDU Deployment Script
:: Version: 0.2.2
:: ----------------------

:: Prerequisites
:: -------------

:: Verify node.js installed
where node 2>nul >nul
IF %ERRORLEVEL% NEQ 0 (
  echo Missing node.js executable, please install node.js, if already installed make sure it can be reached from current environment.
  goto error
)

:: Setup
:: -----

setlocal enabledelayedexpansion

SET ARTIFACTS=%~dp0%..\artifacts

IF NOT DEFINED DEPLOYMENT_SOURCE (
  SET DEPLOYMENT_SOURCE=%~dp0%.
)

IF NOT DEFINED DEPLOYMENT_TARGET (
  SET DEPLOYMENT_TARGET=%ARTIFACTS%\wwwroot
)

IF NOT DEFINED NEXT_MANIFEST_PATH (
  SET NEXT_MANIFEST_PATH=%ARTIFACTS%\manifest

  IF NOT DEFINED PREVIOUS_MANIFEST_PATH (
    SET PREVIOUS_MANIFEST_PATH=%ARTIFACTS%\manifest
  )
)

IF NOT DEFINED KUDU_SYNC_CMD (
  :: Install kudu sync
  echo Installing Kudu Sync
  call npm install kudusync -g --silent
  IF !ERRORLEVEL! NEQ 0 goto error

  :: Locally just running "kuduSync" would also work
  SET KUDU_SYNC_CMD=%appdata%\npm\kuduSync.cmd
)
IF NOT DEFINED DEPLOYMENT_TEMP (
  SET DEPLOYMENT_TEMP=%temp%\___deployTemp%random%
  SET CLEAN_LOCAL_DEPLOYMENT_TEMP=true
)

IF DEFINED CLEAN_LOCAL_DEPLOYMENT_TEMP (
  IF EXIST "%DEPLOYMENT_TEMP%" rd /s /q "%DEPLOYMENT_TEMP%"
  mkdir "%DEPLOYMENT_TEMP%"
)

IF NOT DEFINED MSBUILD_PATH (
  SET MSBUILD_PATH=%WINDIR%\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
)

IF NOT DEFINED POST_DEPLOYMENT_SOURCE (
  SET POST_DEPLOYMENT_SOURCE=%DEPLOYMENT_SOURCE%\Scripts\PostDeploymentActions\
)

IF NOT DEFINED POST_DEPLOYMENT_TARGET (
  SET POST_DEPLOYMENT_TARGET=%DEPLOYMENT_SOURCE%..\deployments\tools\PostDeploymentActions\
  SET CLEAN_POST_DEPLOYMENT_TARGET=true
)

IF DEFINED CLEAN_POST_DEPLOYMENT_TARGET (
  IF EXIST "%POST_DEPLOYMENT_TARGET%" rd /s /q "%POST_DEPLOYMENT_TARGET%"
  mkdir "%POST_DEPLOYMENT_TARGET%"
)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Deployment
:: ----------

echo Handling .NET Web Application deployment.

:: 1. Restore NuGet packages
IF /I "Resume.sln" NEQ "" (
  call :ExecuteCmd nuget restore "%DEPLOYMENT_SOURCE%\Resume.sln"
  IF !ERRORLEVEL! NEQ 0 goto error
)

:: 2. Install npm packages, bower, grunt, and bower packages
IF /I "%IN_PLACE_DEPLOYMENT%" NEQ "1" (
	pushd "%DEPLOYMENT_SOURCE%\Resume"

	echo Installing npm packages...
	call :ExecuteCmd npm install
	IF !ERRORLEVEL! NEQ 0 goto error

	echo Running npm dedupe...
	call :ExecuteCmd npm dedupe
	IF !ERRORLEVEL! NEQ 0 goto error

	echo Installing grunt-cli...
	call :ExecuteCmd npm install grunt-cli -g
	IF !ERRORLEVEL! NEQ 0 goto error

	echo Installing bower...
	call :ExecuteCmd npm install bower -g
	IF !ERRORLEVEL! NEQ 0 goto error

	echo Running bower-install grunt task...
	call :ExecuteCmd grunt bower-install
	IF !ERRORLEVEL! NEQ 0 goto error
	popd
)

:: 3. Build to the temporary path
IF /I "%IN_PLACE_DEPLOYMENT%" NEQ "1" (
  call :ExecuteCmd "%MSBUILD_PATH%" "%DEPLOYMENT_SOURCE%\Resume\Resume.csproj" /nologo /verbosity:m /t:Build /t:pipelinePreDeployCopyAllFilesToOneFolder /p:_PackageTempDir="%DEPLOYMENT_TEMP%";AutoParameterizationWebConfigConnectionStrings=false;Configuration=Release /p:SolutionDir="%DEPLOYMENT_SOURCE%\.\\" %SCM_BUILD_ARGS%
) ELSE (
  call :ExecuteCmd "%MSBUILD_PATH%" "%DEPLOYMENT_SOURCE%\Resume\Resume.csproj" /nologo /verbosity:m /t:Build /p:AutoParameterizationWebConfigConnectionStrings=false;Configuration=Release /p:SolutionDir="%DEPLOYMENT_SOURCE%\.\\" %SCM_BUILD_ARGS%
)

IF !ERRORLEVEL! NEQ 0 goto error

:: 4. KuduSync
IF /I "%IN_PLACE_DEPLOYMENT%" NEQ "1" (
  call :ExecuteCmd "%KUDU_SYNC_CMD%" -v 50 -f "%DEPLOYMENT_TEMP%" -t "%DEPLOYMENT_TARGET%" -n "%NEXT_MANIFEST_PATH%" -p "%PREVIOUS_MANIFEST_PATH%" -i ".git;.hg;.deployment;deploy.cmd"
  IF !ERRORLEVEL! NEQ 0 goto error
)

:: 5. Copy the post deployment scripts
IF /I "%IN_PLACE_DEPLOYMENT%" NEQ "1" (
	echo Copy the post deployment scripts...
	call :ExecuteCmd xcopy %POST_DEPLOYMENT_SOURCE% %POST_DEPLOYMENT_TARGET% /Y
)

goto end

:: Execute command routine that will echo out when error
:ExecuteCmd
setlocal
set _CMD_=%*
call %_CMD_%
if "%ERRORLEVEL%" NEQ "0" echo Failed exitCode=%ERRORLEVEL%, command=%_CMD_%
exit /b %ERRORLEVEL%

:error
endlocal
echo An error has occurred during web site deployment.
call :exitSetErrorLevel
call :exitFromFunction 2>nul

:exitSetErrorLevel
exit /b 1

:exitFromFunction
()

:end
endlocal
echo Finished successfully.

@if "%SCM_TRACE_LEVEL%" NEQ "4" @echo off

:: ----------------------
:: KUDU Deployment Script
:: Version: 0.2.2
:: ----------------------

:: Prerequisites
:: -------------

:: Verify node.js installed
where node 2>nul >nul
IF %ERRORLEVEL% NEQ 0 (
  echo Missing node.js executable, please install node.js, if already installed make sure it can be reached from current environment.
  goto error
)

:: Setup
:: -----

setlocal enabledelayedexpansion

SET ARTIFACTS=%~dp0%..\artifacts

IF NOT DEFINED DEPLOYMENT_SOURCE (
  SET DEPLOYMENT_SOURCE=%~dp0%.
)

IF NOT DEFINED DEPLOYMENT_TARGET (
  SET DEPLOYMENT_TARGET=%ARTIFACTS%\wwwroot
)

IF NOT DEFINED NEXT_MANIFEST_PATH (
  SET NEXT_MANIFEST_PATH=%ARTIFACTS%\manifest

  IF NOT DEFINED PREVIOUS_MANIFEST_PATH (
    SET PREVIOUS_MANIFEST_PATH=%ARTIFACTS%\manifest
  )
)

IF NOT DEFINED KUDU_SYNC_CMD (
  :: Install kudu sync
  echo Installing Kudu Sync
  call npm install kudusync -g --silent
  IF !ERRORLEVEL! NEQ 0 goto error

  :: Locally just running "kuduSync" would also work
  SET KUDU_SYNC_CMD=%appdata%\npm\kuduSync.cmd
)
IF NOT DEFINED DEPLOYMENT_TEMP (
  SET DEPLOYMENT_TEMP=%temp%\___deployTemp%random%
  SET CLEAN_LOCAL_DEPLOYMENT_TEMP=true
)

IF DEFINED CLEAN_LOCAL_DEPLOYMENT_TEMP (
  IF EXIST "%DEPLOYMENT_TEMP%" rd /s /q "%DEPLOYMENT_TEMP%"
  mkdir "%DEPLOYMENT_TEMP%"
)

IF NOT DEFINED MSBUILD_PATH (
  SET MSBUILD_PATH=%WINDIR%\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
)

IF NOT DEFINED POST_DEPLOYMENT_SOURCE (
  SET POST_DEPLOYMENT_SOURCE=%DEPLOYMENT_SOURCE%\Scripts\PostDeploymentActions\
)

IF NOT DEFINED POST_DEPLOYMENT_TARGET (
  SET POST_DEPLOYMENT_TARGET=%DEPLOYMENT_SOURCE%..\deployments\tools\PostDeploymentActions\
  SET CLEAN_POST_DEPLOYMENT_TARGET=true
)

IF DEFINED CLEAN_POST_DEPLOYMENT_TARGET (
  IF EXIST "%POST_DEPLOYMENT_TARGET%" rd /s /q "%POST_DEPLOYMENT_TARGET%"
  mkdir "%POST_DEPLOYMENT_TARGET%"
)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Deployment
:: ----------

echo Handling .NET Web Application deployment.

:: 1. Restore NuGet packages
IF /I "Resume.sln" NEQ "" (
  call :ExecuteCmd nuget restore "%DEPLOYMENT_SOURCE%\Resume.sln"
  IF !ERRORLEVEL! NEQ 0 goto error
)

:: 2. Install npm packages, bower, grunt, and bower packages
IF /I "%IN_PLACE_DEPLOYMENT%" NEQ "1" (
	pushd "%DEPLOYMENT_SOURCE%\Resume"

	echo Installing npm packages...
	call :ExecuteCmd npm install
	IF !ERRORLEVEL! NEQ 0 goto error

	echo Running npm dedupe...
	call :ExecuteCmd npm dedupe
	IF !ERRORLEVEL! NEQ 0 goto error

	echo Installing grunt-cli...
	call :ExecuteCmd npm install grunt-cli -g
	IF !ERRORLEVEL! NEQ 0 goto error

	echo Installing bower...
	call :ExecuteCmd npm install bower -g
	IF !ERRORLEVEL! NEQ 0 goto error

	echo Running bower-install grunt task...
	call :ExecuteCmd grunt bower-install
	IF !ERRORLEVEL! NEQ 0 goto error
	popd
)

:: 3. Build to the temporary path
IF /I "%IN_PLACE_DEPLOYMENT%" NEQ "1" (
  call :ExecuteCmd "%MSBUILD_PATH%" "%DEPLOYMENT_SOURCE%\Resume\Resume.csproj" /nologo /verbosity:m /t:Build /t:pipelinePreDeployCopyAllFilesToOneFolder /p:_PackageTempDir="%DEPLOYMENT_TEMP%";AutoParameterizationWebConfigConnectionStrings=false;Configuration=Release /p:SolutionDir="%DEPLOYMENT_SOURCE%\.\\" %SCM_BUILD_ARGS%
) ELSE (
  call :ExecuteCmd "%MSBUILD_PATH%" "%DEPLOYMENT_SOURCE%\Resume\Resume.csproj" /nologo /verbosity:m /t:Build /p:AutoParameterizationWebConfigConnectionStrings=false;Configuration=Release /p:SolutionDir="%DEPLOYMENT_SOURCE%\.\\" %SCM_BUILD_ARGS%
)

IF !ERRORLEVEL! NEQ 0 goto error

:: 4. KuduSync
IF /I "%IN_PLACE_DEPLOYMENT%" NEQ "1" (
  call :ExecuteCmd "%KUDU_SYNC_CMD%" -v 50 -f "%DEPLOYMENT_TEMP%" -t "%DEPLOYMENT_TARGET%" -n "%NEXT_MANIFEST_PATH%" -p "%PREVIOUS_MANIFEST_PATH%" -i ".git;.hg;.deployment;deploy.cmd"
  IF !ERRORLEVEL! NEQ 0 goto error
)

:: 5. Copy the post deployment scripts
IF /I "%IN_PLACE_DEPLOYMENT%" NEQ "1" (
	echo Copy the post deployment scripts...
	call :ExecuteCmd xcopy %POST_DEPLOYMENT_SOURCE% %POST_DEPLOYMENT_TARGET% /Y
	IF !ERRORLEVEL! NEQ 0 goto error
)

goto end

:: Execute command routine that will echo out when error
:ExecuteCmd
setlocal
set _CMD_=%*
call %_CMD_%
if "%ERRORLEVEL%" NEQ "0" echo Failed exitCode=%ERRORLEVEL%, command=%_CMD_%
exit /b %ERRORLEVEL%

:error
endlocal
echo An error has occurred during web site deployment.
call :exitSetErrorLevel
call :exitFromFunction 2>nul

:exitSetErrorLevel
exit /b 1

:exitFromFunction
()

:end
endlocal
echo Finished successfully.

add exit on error condition in case copying the post deployment action fails


REM use pre-compiled executable for windows
mkdir %PREFIX%\bin

CD chargemol_FORTRAN_09_26_2017
CD sourcecode_windows_command_line

flang.exe -fopenmp -o Chargemol_09_26_2017_windows_parallel ^
  module_precision.f08 ^
  module_global_parameters.f08 ^
  module_common_variable_declarations.f08 ^
  module_quote.f08 ^
  module_string_utilities.f08 ^
  module_matrix_operations.f08 ^
  module_reshaping_functions.f08 ^
  module_CM5_parameters.f08 ^
  module_calculate_atomic_polarizabilities_upper_bound.f08 ^
  module_read_job_control.f08 ^
  module_read_wfx.f08 ^
  module_gaussian_functions.f08 ^
  module_compute_CM5.f08 ^
  module_check_atomic_reference_polarizabilities_available.f08 ^
  module_charge_center_positions_and_parallelpiped.f08 ^
  module_generate_kApoints_kBpoints_kCpoints.f08 ^
  module_check_grid_spacing.f08 ^
  module_add_missing_core_density.f08 ^
  module_oxidation_density.f08 ^
  module_initialize_atomic_densities.f08 ^
  module_align_periodic_atoms.f08 ^
  module_read_spin_density_cube_files.f08 ^
  module_format_valence_and_total_cube_densities.f08 ^
  module_format_valence_cube_density.f08 ^
  module_format_total_cube_density.f08 ^
  module_format_xsf_densities.f08 ^
  module_check_noncollinear_XC_functional.f08 ^
  module_gen_dens_grids_from_gaussian_basis_set_coeff.f08 ^
  module_atomic_symbol_to_number.f08 ^
  module_compute_dominant_atom_volumes.f08 ^
  module_format_vasp_densities.f08 ^
  module_run_valence_core_densities.f08 ^
  module_core_iterator.f08 ^
  module_local_multipole_moment_analysis.f08 ^
  module_update_atomic_densities.f08 ^
  module_DDEC3_valence_iterator.f08 ^
  module_DDEC6_valence_iterator.f08 ^
  module_compute_center_of_mass.f08 ^
  module_total_multipole_moment_analysis.f08 ^
  module_cloud_penetration.f08 ^
  module_atomic_number_to_symbol.f08 ^
  module_generate_atomic_polarizability_upper_bound_file.f08 ^
  module_generate_net_atomic_charge_file.f08 ^
  module_spin_functions.f08 ^
  module_generate_atomic_spin_moment_file.f08 ^
  module_collinear_spin_moments_iterator.f08 ^
  module_noncollinear_spin_moments_iterator.f08 ^
  module_generate_bond_order_file.f08 ^
  module_determine_whether_pair_overlap_is_significant.f08 ^
  module_calculate_final_BOs.f08 ^
  module_integrate_bonding_terms.f08 ^
  module_initialize_bond_pair_matrix.f08 ^
  module_compute_local_atomic_exchange_vectors.f08 ^
  module_prepare_BO_density_grids.f08 ^
  module_perform_bond_order_analysis.f08 ^
  module_compute_atomic_radial_moments.f08 ^
  module_print_overlap_populations.f08 ^
  module_print_atomic_densities_file.f08 ^
  chargemol.f08

COPY Chargemol_09_26_2017_windows_parallel %PREFIX%\bin\chargemol.exe
REM COPY chargemol_FORTRAN_09_26_2017\compiled_binaries\windows\Chargemol_09_26_2017_windows_64bits_parallel_GUI.exe %PREFIX%\bin\chargemol_gui.exe
REM COPY chargemol_FORTRAN_09_26_2017\compiled_binaries\windows\pthreadGC2-64.dll %PREFIX%\bin

CD ..
CD ..

REM install atomic densities directory
mkdir %PREFIX%\share
mkdir %PREFIX%\share\chargemol
XCOPY atomic_densities %PREFIX%\share\chargemol /s /e /y

REM use pre-compiled executable for windows
mkdir %PREFIX%\bin

CD chargemol_FORTRAN_09_26_2017
CD sourcecode_windows_command_line

flang.exe -v -fopenmp -o Chargemol_09_26_2017_windows_parallel ^
  module_precision.f08 ^
  module_global_parameters.f08 ^
  module_common_variable_declarations.f08 ^
  module_quote.f08 ^
  module_string_utilities.f08 ^
  module_matrix_operations.f08 ^
  module_reshaping_functions.f08 ^
  module_CM5_parameters.f08 ^
  module_calculate_atomic_polarizabilities_upper_bound.f08 ^
  module_read_job_control.f08 ^
  module_read_wfx.f08 ^
  module_gaussian_functions.f08 ^
  module_compute_CM5.f08 ^
  module_check_atomic_reference_polarizabilities_available.f08 ^
  module_charge_center_positions_and_parallelpiped.f08 ^
  module_generate_kApoints_kBpoints_kCpoints.f08 ^
  module_check_grid_spacing.f08 ^
  module_add_missing_core_density.f08 ^
  module_oxidation_density.f08 ^
  module_initialize_atomic_densities.f08 ^
  module_align_periodic_atoms.f08 ^
  module_read_spin_density_cube_files.f08 ^
  module_format_valence_and_total_cube_densities.f08 ^
  module_format_valence_cube_density.f08 ^
  module_format_total_cube_density.f08 ^
  module_format_xsf_densities.f08 ^
  module_check_noncollinear_XC_functional.f08 ^
  module_gen_dens_grids_from_gaussian_basis_set_coeff.f08 ^
  module_atomic_symbol_to_number.f08 ^
  module_compute_dominant_atom_volumes.f08 ^
  module_format_vasp_densities.f08 ^
  module_run_valence_core_densities.f08 ^
  module_core_iterator.f08 ^
  module_local_multipole_moment_analysis.f08 ^
  module_update_atomic_densities.f08 ^
  module_DDEC3_valence_iterator.f08 ^
  module_DDEC6_valence_iterator.f08 ^
  module_compute_center_of_mass.f08 ^
  module_total_multipole_moment_analysis.f08 ^
  module_cloud_penetration.f08 ^
  module_atomic_number_to_symbol.f08 ^
  module_generate_atomic_polarizability_upper_bound_file.f08 ^
  module_generate_net_atomic_charge_file.f08 ^
  module_spin_functions.f08 ^
  module_generate_atomic_spin_moment_file.f08 ^
  module_collinear_spin_moments_iterator.f08 ^
  module_noncollinear_spin_moments_iterator.f08 ^
  module_generate_bond_order_file.f08 ^
  module_determine_whether_pair_overlap_is_significant.f08 ^
  module_calculate_final_BOs.f08 ^
  module_integrate_bonding_terms.f08 ^
  module_initialize_bond_pair_matrix.f08 ^
  module_compute_local_atomic_exchange_vectors.f08 ^
  module_prepare_BO_density_grids.f08 ^
  module_perform_bond_order_analysis.f08 ^
  module_compute_atomic_radial_moments.f08 ^
  module_print_overlap_populations.f08 ^
  module_print_atomic_densities_file.f08 ^
  chargemol.f08

COPY Chargemol_09_26_2017_windows_parallel %PREFIX%\bin\chargemol.exe
REM COPY chargemol_FORTRAN_09_26_2017\compiled_binaries\windows\Chargemol_09_26_2017_windows_64bits_parallel_GUI.exe %PREFIX%\bin\chargemol_gui.exe
REM COPY chargemol_FORTRAN_09_26_2017\compiled_binaries\windows\pthreadGC2-64.dll %PREFIX%\bin

CD ..
CD ..

REM install atomic densities directory
mkdir %PREFIX%\share
mkdir %PREFIX%\share\chargemol
XCOPY atomic_densities %PREFIX%\share\chargemol /s /e /y

add -v

add -v


@ECHO OFF
PUSHD %~dp0

SETLOCAL
SETLOCAL ENABLEDELAYEDEXPANSION

:: Check if node exists globally
WHERE node >NUL
IF NOT '%ERRORLEVEL%'=='0' (
    ECHO ERROR: UpdateVersion.cmd requires node installed globally.
    GOTO :Exit
)

:: Check if git exists globally
WHERE git >NUL
IF NOT '%ERRORLEVEL%'=='0' (
    ECHO ERROR: UpdateVersion.cmd requires git installed globally.
    GOTO :Exit
)

:GetBranch

FOR /F %%i in ('git rev-parse --abbrev-ref HEAD') DO (
    SET BRANCH=%%i
    ECHO CURRENT BRANCH: !BRANCH!
)

:GetVersion
SET MainVersion=
FOR /F "tokens=5 delims=:) " %%i in (RELEASENOTE.md) DO (
    SET MainVersion=%%i
    GOTO :GetGitVersion
)

IF NOT DEFINED MainVersion (
    ECHO ERROR: Unable to get main version from release note
    GOTO :Exit
)

:GetGitVersion
IF '%BRANCH%'=='master' (
    ECHO For master branch, use release version
    SET VERSION=!MainVersion!.0
    FOR /F "tokens=2 delims=-" %%i in ('git describe') DO (
        SET VERSION=!MainVersion!.%%i
        ECHO CURRENT VERSION: !VERSION!
    )

) ELSE (
    ECHO For branch other than master, use alpha version
    SET VERSION=!MainVersion!.0-alpha
    FOR /F "tokens=2,3 delims=-" %%i in ('git describe') DO (
        SET VERSION=!MainVersion!.%%i-alpha-%%j
        ECHO CURRENT VERSION:!VERSION!
    )
)

IF NOT '%ERRORLEVEL%'=='0' (
    ECHO ERROR: Unable to get version from git describe
    GOTO :Exit
)

:UpdateVersion
mkdir TEMP 2>NUL
ECHO %VERSION% > TEMP\version.txt
PUSHD tools
:: Install npm packages
CALL npm install

:: GRUNT to generate nuget packages
CALL node node_modules/grunt-cli/bin/grunt updateVersion --uv=%VERSION%

IF NOT '%ErrorLevel%'=='0' (
    ECHO ERROR: Unable to update version
    GOTO :Exit
)
POPD

:Exit
POPD
ECHO.

EXIT /B %ERRORLEVEL%

@ECHO OFF
PUSHD %~dp0

SETLOCAL
SETLOCAL ENABLEDELAYEDEXPANSION

:: Check if node exists globally
WHERE node >NUL
IF NOT '%ERRORLEVEL%'=='0' (
    ECHO ERROR: UpdateVersion.cmd requires node installed globally.
    GOTO :Exit
)

:: Check if git exists globally
WHERE git >NUL
IF NOT '%ERRORLEVEL%'=='0' (
    ECHO ERROR: UpdateVersion.cmd requires git installed globally.
    GOTO :Exit
)

:GetBranch

FOR /F %%i in ('git rev-parse --abbrev-ref HEAD') DO (
    SET BRANCH=%%i
    ECHO CURRENT BRANCH: !BRANCH!
)

:GetVersion
SET MainVersion=
FOR /F "tokens=5 delims=:) " %%i in (RELEASENOTE.md) DO (
    SET MainVersion=%%i
    GOTO :GetGitVersion
)

IF NOT DEFINED MainVersion (
    ECHO ERROR: Unable to get main version from release note
    GOTO :Exit
)

:GetGitVersion
IF '%BRANCH%'=='master' (
    ECHO For master branch, use release version
    SET VERSION=!MainVersion!.0
    FOR /F "tokens=2 delims=-" %%i in ('git describe') DO (
        SET VERSION=!MainVersion!.%%i
        ECHO CURRENT VERSION: !VERSION!
    )

) ELSE (
    ECHO For branch other than master, use alpha version
    SET VERSION=!MainVersion!.0-alpha
    FOR /F "tokens=2,3 delims=-" %%i in ('git describe') DO (
        SET VERSION=!MainVersion!.0-alpha-%%i-%%j
        ECHO CURRENT VERSION:!VERSION!
    )
)

IF NOT '%ERRORLEVEL%'=='0' (
    ECHO ERROR: Unable to get version from git describe
    GOTO :Exit
)

:UpdateVersion
mkdir TEMP 2>NUL
ECHO %VERSION% > TEMP\version.txt
PUSHD tools
:: Install npm packages
CALL npm install

:: GRUNT to generate nuget packages
CALL node node_modules/grunt-cli/bin/grunt updateVersion --uv=%VERSION%

IF NOT '%ErrorLevel%'=='0' (
    ECHO ERROR: Unable to update version
    GOTO :Exit
)
POPD

:Exit
POPD
ECHO.

EXIT /B %ERRORLEVEL%

Change version logic in branches other than master


rd /S /Q Web2ExeWin
del *.zip
call pyinstaller --onefile ^
 --hidden-import PIL.Jpeg2KImagePlugin ^
 --hidden-import configobj ^
 --hidden-import pkg_resources ^
 -i images\icon.ico ^
 --distpath Web2ExeWin-CMD ^
 -n web2exe-win command_line.py

rd /S /Q Web2ExeWin-CMD\files
echo D | xcopy /s files Web2ExeWin-CMD\files

call pyinstaller -w --onefile ^
 --hidden-import PIL.Jpeg2KImagePlugin ^
 --hidden-import pkg_resources ^
 --hidden-import configobj ^
 -i images\icon.ico ^
 --distpath Web2ExeWin -n Web2Exe main.py

echo D | xcopy /s files Web2ExeWin\files

del Web2ExeWin\files\compressors\upx-mac
del Web2ExeWin\files\compressors\upx-linux-x64
del Web2ExeWin\files\compressors\upx-linux-x32

del Web2ExeWin-CMD\files\compressors\upx-mac
del Web2ExeWin-CMD\files\compressors\upx-linux-x64
del Web2ExeWin-CMD\files\compressors\upx-linux-x32

makensis /V4 scripts/Web2Exe.nsi

set /p Version=<files\version.txt

7z a Web2ExeWin-%Version%.zip -r Web2ExeWin
cd Web2ExeWin-CMD
7z a ..\Web2ExeWin-CMD.zip -tzip -r *
cd ..
7z a Web2ExeWin-Setup.zip Web2Exe-Setup.exe

call python scripts/upload_release.py

rd /S /Q Web2ExeWin
rd /S /Q build
del *.zip
call pyinstaller --onefile ^
 --hidden-import PIL.Jpeg2KImagePlugin ^
 --hidden-import configobj ^
 --hidden-import pkg_resources ^
 -i images\icon.ico ^
 --distpath Web2ExeWin-CMD ^
 -n web2exe-win command_line.py

rd /S /Q Web2ExeWin-CMD\files
echo D | xcopy /s files Web2ExeWin-CMD\files

call pyinstaller -w --onefile ^
 --hidden-import PIL.Jpeg2KImagePlugin ^
 --hidden-import pkg_resources ^
 --hidden-import configobj ^
 -i images\icon.ico ^
 --distpath Web2ExeWin -n Web2Exe main.py

echo D | xcopy /s files Web2ExeWin\files

del Web2ExeWin\files\compressors\upx-mac
del Web2ExeWin\files\compressors\upx-linux-x64
del Web2ExeWin\files\compressors\upx-linux-x32

del Web2ExeWin-CMD\files\compressors\upx-mac
del Web2ExeWin-CMD\files\compressors\upx-linux-x64
del Web2ExeWin-CMD\files\compressors\upx-linux-x32

makensis /V4 scripts/Web2Exe.nsi

set /p Version=<files\version.txt

7z a Web2ExeWin-%Version%.zip -r Web2ExeWin
cd Web2ExeWin-CMD
7z a ..\Web2ExeWin-CMD.zip -tzip -r *
cd ..
7z a Web2ExeWin-Setup.zip Web2Exe-Setup.exe

call python scripts/upload_release.py

Remove build folder for windows

Remove build folder for windows


REM build script for MyGet builds

set config=%1
if "%config%" == "" (
   set config=Release
)

REM Restore packages
call powershell "& .\nuget-restore.ps1"

REM Detect MSBuild 15.0 path
if exist "%programfiles(x86)%\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\MSBuild.exe" (
    set msbuild="%programfiles(x86)%\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\MSBuild.exe"
)
if exist "%programfiles(x86)%\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe" (
    set msbuild="%programfiles(x86)%\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe"
)
if exist "%programfiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe" (
    set msbuild="%programfiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe"
)

REM *** NOTE *** When running this locally, use the version without the quotes.
REM              MyGet requires the quotes, but the command line doesn't like them.  Don't ask me...

call %msbuild% Manatee.Json.sln /p:Configuration="%config%" /m:1 /v:m /fl /flp:LogFile=msbuild.log;Verbosity=Normal /nr:false
REM call "%msbuild%" Manatee.Json.sln /p:Configuration="%config%" /m:1 /v:m /fl /flp:LogFile=msbuild.log;Verbosity=Normal /nr:false

REM Package
call %msbuild% Manatee.Json\Manatee.Json.csproj /t:pack /p:Configuration=Release
REM call "%msbuild%" Manatee.Json\Manatee.Json.csproj /t:pack /p:Configuration=Release

copy Manatee.Json\bin\%config%\*.nupkg . /Y

REM build script for MyGet builds

set config=%1
if "%config%" == "" (
   set config=Release
)

REM Restore packages
call powershell "& .\nuget-restore.ps1"

REM Detect MSBuild 15.0 path
if exist "%programfiles(x86)%\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\MSBuild.exe" (
    set msbuild="%programfiles(x86)%\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\MSBuild.exe"
)
if exist "%programfiles(x86)%\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe" (
    set msbuild="%programfiles(x86)%\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe"
)
if exist "%programfiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe" (
    set msbuild="%programfiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe"
)

REM *** NOTE *** When running this locally, use the version without the quotes.
REM              MyGet requires the quotes, but the command line doesn't like them.  Don't ask me...

REM call %msbuild% Manatee.Json.sln /p:Configuration="%config%" /m:1 /v:m /fl /flp:LogFile=msbuild.log;Verbosity=Normal /nr:false
call "%msbuild%" Manatee.Json.sln /p:Configuration="%config%" /m:1 /v:m /fl /flp:LogFile=msbuild.log;Verbosity=Normal /nr:false

REM Package
REM call %msbuild% Manatee.Json\Manatee.Json.csproj /t:pack /p:Configuration=Release
call "%msbuild%" Manatee.Json\Manatee.Json.csproj /t:pack /p:Configuration=Release

copy Manatee.Json\bin\%config%\*.nupkg . /Y

fix quotes in build script

fix quotes in build script


REM @echo Off
set config=%1
if "%config%" == "" (
   set config=Release
)

set version=1.0.0
if not "%PackageVersion%" == "" (
   set version=%PackageVersion%
)

set nuget=
if "%nuget%" == "" (
	set nuget=nuget
)

dir

echo "========"
echo %WINDIR%

nuget restore Sigma.sln

%WINDIR%\Microsoft.NET\Framework\v4.0.30319\msbuild Sigma.sln /p:Configuration="%config%" /m /v:M /fl /flp:LogFile=msbuild.log;Verbosity=diag /nr:false

REM pack Sigma.Core

cd Sigma.Core
nuget pack "Sigma.Core.csproj" -IncludeReferencedProjects -Prop Platform=x64 -Verbosity detailed -Prop Configuration=%config% -Version %version%

cd ..

REM pack Sigma.Core.Monitors.WPF

cd Sigma.Core.Monitors.WPF

REM update the targets file

cd build
powershell -Command "(gc Sigma.Core.Monitors.WPF.targets) -replace '~version~', '%version%' | Out-File Sigma.Core.Monitors.WPF.targets"

cd ..
nuget pack "Sigma.Core.Monitors.WPF.csproj" -IncludeReferencedProjects -Prop Platform=x64 -Verbosity detailed -Prop Configuration=%config% -Version %version%

REM @echo Off
set config=%1
if "%config%" == "" (
   set config=Release
)

set version=1.0.0
if not "%PackageVersion%" == "" (
   set version=%PackageVersion%
)

set nuget=
if "%nuget%" == "" (
	set nuget=nuget
)

dir

echo "========"
echo %WINDIR%

powershell -Command "(new-object System.Net.WebClient).DownloadFile('https://dist.nuget.org/win-x86-commandline/latest/nuget.exe','nuget.exe')"

nuget.exe restore Sigma.sln

%WINDIR%\Microsoft.NET\Framework\v4.0.30319\msbuild Sigma.sln /p:Configuration="%config%" /m /v:M /fl /flp:LogFile=msbuild.log;Verbosity=diag /nr:false

REM pack Sigma.Core

cd Sigma.Core
nuget.exe pack "Sigma.Core.csproj" -IncludeReferencedProjects -Prop Platform=x64 -Verbosity detailed -Prop Configuration=%config% -Version %version%

cd ..

REM pack Sigma.Core.Monitors.WPF

cd Sigma.Core.Monitors.WPF

REM update the targets file

cd build
powershell -Command "(gc Sigma.Core.Monitors.WPF.targets) -replace '~version~', '%version%' | Out-File Sigma.Core.Monitors.WPF.targets"

cd ..
nuget.exe pack "Sigma.Core.Monitors.WPF.csproj" -IncludeReferencedProjects -Prop Platform=x64 -Verbosity detailed -Prop Configuration=%config% -Version %version%

Update nuget version

Update nuget version


@setlocal EnableDelayedExpansion EnableExtensions
@for %%i in (%~dp0\_packer_config*.cmd) do @call "%%~i"
@if defined PACKER_DEBUG (@echo on) else (@echo off)

title Enabling Windows Remote Management. Please wait...

echo ==^> Turning off User Account Control (UAC)
:: see http://www.howtogeek.com/howto/windows-vista/enable-or-disable-uac-from-the-windows-vista-command-line/
reg ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: reg ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f

title Enabling Windows Remote Management. Please wait...

echo ==^> Setting the PowerShell ExecutionPolicy to RemoteSigned (64 bit)
powershell -Command "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force" <NUL
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: powershell -Command "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force"

if exist %SystemRoot%\SysWOW64\cmd.exe (
  echo ==^> Setting the PowerShell ExecutionPolicy to RemoteSigned (32 bit)
  %SystemRoot%\SysWOW64\cmd.exe /c powershell -Command "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force" <NUL
  @if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: powershell -Command "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force"
)

:: systeminfo 2>nul | findstr /b /c:"OS Name" | findstr /c:"Windows 7" >nul
:: if errorlevel 1 goto skip_fixnetwork

if not exist a:\fixnetwork.ps1 echo ==^> ERROR: File not found: a:\fixnetwork.ps1

echo ==^> Setting the Network Location to private
:: see http://blogs.msdn.com/b/powershell/archive/2009/04/03/setting-network-location-to-private.aspx
powershell -File a:\fixnetwork.ps1 <NUL
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: powershell -File a:\fixnetwork.ps1

:skip_fixnetwork

echo ==^> Changing remote UAC account policy
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f

echo ==^> Blocking WinRM port 5985 on the firewall
netsh advfirewall firewall add rule name="winrm"  dir=in action=block protocol=TCP localport=5985
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: netsh advfirewall firewall add rule name="winrm"  dir=in action=block protocol=TCP localport=5985

echo ==^> Configuring Windows Remote Management (WinRM) service

call winrm quickconfig -q
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm quickconfig -q

call winrm quickconfig -transport:http
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm quickconfig -transport:http

call winrm set winrm/config @{MaxTimeoutms="1800000"}
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm set winrm/config @{MaxTimeoutms="1800000"}

call winrm set winrm/config/winrs @{MaxMemoryPerShellMB="800"}
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm set winrm/config/winrs @{MaxMemoryPerShellMB="1024"}

call winrm set winrm/config/service @{AllowUnencrypted="true"}
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm set winrm/config/service @{AllowUnencrypted="true"}

call winrm set winrm/config/service/auth @{Basic="true"}
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm set winrm/config/service/auth @{Basic="true"}

call winrm set winrm/config/client/auth @{Basic="true"}
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm set winrm/config/client/auth @{Basic="true"}

call winrm set winrm/config/listener?Address=*+Transport=HTTP @{Port="5985"}
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm set winrm/config/listener?Address=*+Transport=HTTP @{Port="5985"}

sc config winrm start= auto
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: sc config winrm start= auto

:: wait for winrm service to finish starting
timeout 5

sc query winrm | findstr "RUNNING" >nul
if errorlevel 1 goto winrm_not_running

echo ==^> Stopping winrm service

sc stop winrm

:is_winrm_running

timeout 1

sc query winrm | findstr "STOPPED" >nul
if errorlevel 1 goto is_winrm_running

:winrm_not_running

echo ==^> Unblocking WinRM port 5985 on the firewall
netsh advfirewall firewall delete rule name="winrm"
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: netsh advfirewall firewall delete rule name="winrm"

echo ==^> Enable firewall groups
:: see http://social.technet.microsoft.com/Forums/windowsserver/en-US/a1e65f0f-2550-49ae-aee2-56a9bdcfb8fb/windows-7-remote-administration-firewall-group?forum=winserverManagement
ver | findstr /i "6\.[2-9]\."
if errorlevel 1 (
  echo ==^> Enabling Remote Administration firewall group
  :: pre win 8/server 2012
  netsh advfirewall firewall set rule group="remote administration" new enable=yes
  @if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: netsh advfirewall firewall set rule group="remote administration" new enable=yes
) else (
  echo ==^> Enabling Windows Remote Management firewall group
  :: win 8+/server 2012+
  netsh advfirewall firewall set rule group="Windows Remote Management" new enable=yes
  @if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: netsh advfirewall firewall set rule group="Windows Remote Management" new enable=yes
)

netsh advfirewall firewall add rule name="winrm" dir=in action=allow protocol=TCP localport=5985
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: netsh advfirewall firewall add rule name="winrm"  dir=in action=allow protocol=TCP localport=5985

:: wait for firewall groups to enable
timeout 5

:exit0

ver>nul

goto :exit

:exit1

verify other 2>nul

:exit

@setlocal EnableDelayedExpansion EnableExtensions
@for %%i in (%~dp0\_packer_config*.cmd) do @call "%%~i"
@if defined PACKER_DEBUG (@echo on) else (@echo off)

title Enabling Windows Remote Management. Please wait...

echo ==^> Turning off User Account Control (UAC)
:: see http://www.howtogeek.com/howto/windows-vista/enable-or-disable-uac-from-the-windows-vista-command-line/
reg ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: reg ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f

title Enabling Windows Remote Management. Please wait...

echo ==^> Setting the PowerShell ExecutionPolicy to RemoteSigned (64 bit)
powershell -Command "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force" <NUL
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: powershell -Command "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force"

if exist %SystemRoot%\SysWOW64\cmd.exe (
  echo ==^> Setting the PowerShell ExecutionPolicy to RemoteSigned (32 bit)
  %SystemRoot%\SysWOW64\cmd.exe /c powershell -Command "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force" <NUL
  @if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: powershell -Command "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force"
)

:: systeminfo 2>nul | findstr /b /c:"OS Name" | findstr /c:"Windows 7" >nul
:: if errorlevel 1 goto skip_fixnetwork

if not exist a:\fixnetwork.ps1 echo ==^> ERROR: File not found: a:\fixnetwork.ps1

echo ==^> Setting the Network Location to private
:: see http://blogs.msdn.com/b/powershell/archive/2009/04/03/setting-network-location-to-private.aspx
powershell -File a:\fixnetwork.ps1 <NUL
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: powershell -File a:\fixnetwork.ps1

:skip_fixnetwork

echo ==^> Changing remote UAC account policy
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f

echo ==^> Blocking WinRM port 5985 on the firewall
netsh advfirewall firewall add rule name="winrm"  dir=in action=block protocol=TCP localport=5985
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: netsh advfirewall firewall add rule name="winrm"  dir=in action=block protocol=TCP localport=5985

echo ==^> Configuring Windows Remote Management (WinRM) service

call winrm quickconfig -q
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm quickconfig -q

call winrm quickconfig -transport:http
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm quickconfig -transport:http

call winrm set winrm/config @{MaxTimeoutms="1800000"}
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm set winrm/config @{MaxTimeoutms="1800000"}

call winrm set winrm/config/winrs @{MaxMemoryPerShellMB="1024"}
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm set winrm/config/winrs @{MaxMemoryPerShellMB="1024"}

call winrm set winrm/config/service @{AllowUnencrypted="true"}
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm set winrm/config/service @{AllowUnencrypted="true"}

call winrm set winrm/config/service/auth @{Basic="true"}
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm set winrm/config/service/auth @{Basic="true"}

call winrm set winrm/config/client/auth @{Basic="true"}
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm set winrm/config/client/auth @{Basic="true"}

call winrm set winrm/config/listener?Address=*+Transport=HTTP @{Port="5985"}
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: winrm set winrm/config/listener?Address=*+Transport=HTTP @{Port="5985"}

sc config winrm start= auto
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: sc config winrm start= auto

:: wait for winrm service to finish starting
timeout 5

sc query winrm | findstr "RUNNING" >nul
if errorlevel 1 goto winrm_not_running

echo ==^> Stopping winrm service
sc stop winrm

:is_winrm_running

timeout 1

sc query winrm | findstr "STOPPED" >nul
if errorlevel 1 goto is_winrm_running

:winrm_not_running

echo ==^> Unblocking WinRM port 5985 on the firewall
netsh advfirewall firewall delete rule name="winrm"
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: netsh advfirewall firewall delete rule name="winrm"

timeout 1

echo ==^> Enable firewall groups
:: see http://social.technet.microsoft.com/Forums/windowsserver/en-US/a1e65f0f-2550-49ae-aee2-56a9bdcfb8fb/windows-7-remote-administration-firewall-group?forum=winserverManagement
ver | findstr /i "6\.[2-9]\." >nul
if errorlevel 1 (
  echo ==^> Enabling Remote Administration firewall group
  :: pre win 8/server 2012
  netsh advfirewall firewall set rule group="remote administration" new enable=yes
  @if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: netsh advfirewall firewall set rule group="remote administration" new enable=yes
) else (
  echo ==^> Enabling Windows Remote Management firewall group
  :: win 8+/server 2012+
  netsh advfirewall firewall set rule group="Windows Remote Management" new enable=yes
  @if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: netsh advfirewall firewall set rule group="Windows Remote Management" new enable=yes
)

netsh advfirewall firewall add rule name="winrm" dir=in action=allow protocol=TCP localport=5985
@if errorlevel 1 echo ==^> WARNING: Error %ERRORLEVEL% was returned by: netsh advfirewall firewall add rule name="winrm"  dir=in action=allow protocol=TCP localport=5985

echo ==^> Starting winrm service
sc start winrm

:: wait for winrm service to finish starting
timeout 5

:exit0

ver>nul

goto :exit

:exit1

verify other 2>nul

:exit

increase MaxMemoryPerShellMB, add winrm start functionality


Add a ghci wrapper for include paths

Add a ghci wrapper for include paths


if NOT DEFINED ClientRevision set ClientRevision=master
if NOT DEFINED KBFSRevision set KBFSRevision=master
if NOT DEFINED UpdaterRevision set UpdaterRevision=master
if NOT DEFINED ReleaseRevision set ReleaseRevision=master

set OUTPUT=echo
if DEFINED SlackBot set OUTPUT=go run %GOPATH%/src/github.com/keybase/slackbot/send/main.go -i=1

if NOT DEFINED DOKAN_PATH set DOKAN_PATH=%GOPATH%\bin\dokan-dev\build84
echo DOKAN_PATH %DOKAN_PATH%

if NOT DEFINED DevEnvDir call "%ProgramFiles(x86)%\\Microsoft Visual Studio 14.0\\vc\\bin\\vcvars32.bat"

:: Test run saltpack signer to fail early if the key is not correct
go run %GOPATH%\src\github.com\keybase\client\go\tools\ssss\main.go $0
IF %ERRORLEVEL% NEQ 0 (
  echo Saltpack key not set right, can't build
  EXIT /B 1
)

IF [%UpdateChannel%] == [] goto:donecheckingdrivers

IF [%UpdateChannel%] == [None] goto:donecheckingdrivers

IF [%UpdateChannel%] == [Test] goto:donecheckingdrivers

:: don't bother with ci or checking out source, etc. for smoke2 build
IF [%UpdateChannel%] == [Smoke2] goto:done_ci

:: Verify driver signing
:: Check both the built .sys files and the msi package.
if NOT DEFINED UNARCHIVE_COMMAND set UNARCHIVE_COMMAND="C:\Program Filess (x86)\7-Zip\7z" e -y

signtool verify /all /kp /v %DOKAN_PATH%\\x64\\Win10Release\\dokan1.sys | find "Issued to: Microsoft Windows Hardware Compatibility Publisher"
IF %ERRORLEVEL% NEQ 0 goto:build_error || EXIT /B 1
signtool verify /all /kp /v %DOKAN_PATH%\\Win32\\Win10Release\\dokan1.sys | find "Issued to: Microsoft Windows Hardware Compatibility Publisher"
IF %ERRORLEVEL% NEQ 0 goto:build_error || EXIT /B 1
%UNARCHIVE_COMMAND% %DOKAN_PATH%\\dokan_wix\\bin\\x64\\release\\Dokan_x64.msi Win10_Sys
IF %ERRORLEVEL% NEQ 0 goto:build_error || EXIT /B 1
signtool verify /all /kp /v Win10_Sys | find "Issued to: Microsoft Windows Hardware Compatibility Publisher"
IF %ERRORLEVEL% NEQ 0 goto:build_error || EXIT /B 1
%UNARCHIVE_COMMAND% %DOKAN_PATH%\\dokan_wix\\bin\\x86\\release\\Dokan_x86.msi Win10_Sys
IF %ERRORLEVEL% NEQ 0 goto:build_error || EXIT /B 1
signtool verify /all /kp /v Win10_Sys | find "Issued to: Microsoft Windows Hardware Compatibility Publisher"
IF %ERRORLEVEL% NEQ 0 goto:build_error || EXIT /B 1

:donecheckingdrivers

:: NOTE: We depend on the bot or caller to checkout client first
:: call:checkout_keybase client, %ClientRevision% || goto:build_error || EXIT /B 1
call:checkout_keybase kbfs, %KBFSRevision% || goto:build_error || EXIT /B 1
call:checkout_keybase go-updater, %UpdaterRevision% || goto:build_error || EXIT /B 1
call:checkout_keybase release, %ReleaseRevision% || goto:build_error || EXIT /B 1

::wait for CI
if [%UpdateChannel%] == [SmokeCI] call:check_ci  || EXIT /B 1

:done_ci

for /F delims^=^"^ tokens^=2 %%x in ('findstr /C:"Version = " %GOPATH%\src\github.com\keybase\client\go\libkb\version.go') do set LIBKB_VER=%%x

:: release
pushd %GOPATH%\src\github.com\keybase\release
del release.exe
go build
IF %ERRORLEVEL% NEQ 0 (
  goto:build_error || EXIT /B 1
)
for /f %%i in ('release winbuildnumber --version=%LIBKB_VER%') do set BUILD_NUMBER=%%i
echo %BUILD_NUMBER%
popd

if NOT DEFINED BUILD_NUMBER (
  echo bad build number
  goto:build_error || EXIT /B 1
)
:: ensure it's numeric
SET "badbuildnumber="&for /f "delims=0123456789" %%i in ("%BUILD_NUMBER%") do set badbuildnumber=%%i
if defined badbuildnumber (
  echo bad build number
  goto:build_error || EXIT /B 1
)

call %GOPATH%\src\github.com\keybase\client\packaging\windows\build_prerelease.cmd || goto:build_error || EXIT /B 1

::RunQuiet Utility
pushd %GOPATH%\src\github.com\keybase\client\go\tools\runquiet
del rq.hash
del old.hash
powershell -command "wget https://s3.amazonaws.com/prerelease.keybase.io/windows-support/runquiet/runquiet.hash -OutFile old.hash"
git log -1 -- runquiet.go > rq.hash
fc rq.hash old.hash
if %ERRORLEVEL% EQU 0 (
    echo "downloading keybaserq"
    powershell -command "wget https://s3.amazonaws.com/prerelease.keybase.io/windows-support/runquiet/keybaserq.exe -OutFile keybaserq.exe"
) else (
    echo "--- runquiet hashes differ, building keybaserq. Server hash: ---"
    type old.hash
    echo "--- Current hash: ---"
    type rq.hash
    call ..\..\..\packaging\windows\buildrq.bat || goto:build_error || EXIT /B 1
)
popd

call %GOPATH%\src\github.com\keybase\client\packaging\windows\buildui.bat || goto:build_error || EXIT /B 1

::Build Installer
call %GOPATH%\src\github.com\keybase\client\packaging\windows\doinstaller_wix.cmd || goto:build_error || EXIT /B 1

::Publish to S3
if %UpdateChannel% NEQ "None" (
    echo "Uploading %BUILD_TAG%"
    s3browser-con upload prerelease.keybase.io  %GOPATH%\src\github.com\keybase\client\packaging\windows\%BUILD_TAG%\Keybase_%BUILD_TAG%.386.exe prerelease.keybase.io/windows  || goto:build_error || EXIT /B 1
    :: Test channel json
    s3browser-con upload prerelease.keybase.io  %GOPATH%\src\github.com\keybase\client\packaging\windows\%BUILD_TAG%\update-windows-prod-test-v2.json prerelease.keybase.io || goto:build_error || EXIT /B 1
) else (
    echo "No update channel"
)

::Invoke SmokeB build
if [%UpdateChannel%] NEQ [Smoke] (
    if [%UpdateChannel%] NEQ [SmokeCI] (
        echo "Not a smoke build"
        goto :no_smokea
    )
)

:: Smoke A json
s3browser-con upload prerelease.keybase.io  %GOPATH%\src\github.com\keybase\client\packaging\windows\%BUILD_TAG%\*.json prerelease.keybase.io/windows-support || goto:build_error || EXIT /B 1

set PrevUpdateChannel=%UpdateChannel%
set UpdateChannel=Smoke2
set smokeASemVer=%KEYBASE_VERSION%
::SlackBot?

::build again
call %GOPATH%\src\github.com\keybase\client\packaging\windows\dorelease.cmd || EXIT /B 1

:: and we're done here

EXIT /B 0

:no_smokea

::Publish smoke updater jsons to S3
if [%UpdateChannel%] NEQ [Smoke2] (
    echo "Non Smoke2 build"
    %OUTPUT% "Successfully built Windows with client: %KEYBASE_VERSION%, kbfs: %KBFS_BUILD%"
    goto :no_smokeb
)
::Smoke B json
s3browser-con upload prerelease.keybase.io  %GOPATH%\src\github.com\keybase\client\packaging\windows\%BUILD_TAG%\*.json prerelease.keybase.io/windows-support  || goto:build_error || EXIT /B 1
set smokeBSemVer=%KEYBASE_VERSION%
%GOPATH%\src\github.com\keybase\release\release announce-build --build-a="%SmokeASemVer%" --build-b="%smokeBSemVer%" --platform="windows" || goto:build_error || EXIT /B 1
%OUTPUT% "Successfully built Windows: --build-a=%SmokeASemVer% --build-b=%smokeBSemVer%
:no_smokeb

echo %ERRORLEVEL%

goto:eof

:checkout_keybase

if EXIST %GOPATH%\src\github.com\keybase\%~1 goto:repoexists
pushd %GOPATH%\src\github.com\keybase
git clone https://github.com/keybase/%~1.git
popd
:repoexists

pushd %GOPATH%\src\github.com\keybase\%~1
git checkout master || EXIT /B 1
git pull || EXIT /B 1
git checkout %~2 || EXIT /B 1
popd
EXIT /B 0

goto:eof

:build_error
%OUTPUT% "Error building Windows"
EXIT /B 1

:check_ci
for /f %%i in ('git -C %GOPATH%\src\github.com\keybase\client rev-parse --short HEAD') do set clientCommit=%%i
for /f %%i in ('git -C %GOPATH%\src\github.com\keybase\kbfs rev-parse --short HEAD') do set kbfsCommit=%%i
echo [%clientCommit%] [%kbfsCommit%]
:: need GITHUB_TOKEN
pushd %GOPATH%\src\github.com\keybase\release
go build || goto:build_error || EXIT /B 1
release wait-ci --repo="client" --commit="%clientCommit%" --context="continuous-integration/jenkins/branch" --context="ci/circleci"  || goto:ci_error
release wait-ci --repo="kbfs" --commit="%kbfsCommit%" --context="continuous-integration/jenkins/branch" --context="ci/circleci"  || goto:ci_error
popd
EXIT /B 0

:ci_error
%OUTPUT% "CI Failure building Windows"
EXIT /B 1

if NOT DEFINED ClientRevision set ClientRevision=master
if NOT DEFINED KBFSRevision set KBFSRevision=master
if NOT DEFINED UpdaterRevision set UpdaterRevision=master
if NOT DEFINED ReleaseRevision set ReleaseRevision=master

set OUTPUT=echo
if DEFINED SlackBot set OUTPUT=go run %GOPATH%/src/github.com/keybase/slackbot/send/main.go -i=1

if NOT DEFINED DOKAN_PATH set DOKAN_PATH=%GOPATH%\bin\dokan-dev\build84
echo DOKAN_PATH %DOKAN_PATH%

if NOT DEFINED DevEnvDir call "%ProgramFiles(x86)%\\Microsoft Visual Studio 14.0\\vc\\bin\\vcvars32.bat"

IF [%UpdateChannel%] == [] goto:donecheckingdrivers

IF [%UpdateChannel%] == [None] goto:donecheckingdrivers

IF [%UpdateChannel%] == [Test] goto:donecheckingdrivers

:: don't bother with ci or checking out source, etc. for smoke2 build
IF [%UpdateChannel%] == [Smoke2] goto:done_ci

:: Verify driver signing
:: Check both the built .sys files and the msi package.
if NOT DEFINED UNARCHIVE_COMMAND set UNARCHIVE_COMMAND="C:\Program Filess (x86)\7-Zip\7z" e -y

signtool verify /all /kp /v %DOKAN_PATH%\\x64\\Win10Release\\dokan1.sys | find "Issued to: Microsoft Windows Hardware Compatibility Publisher"
IF %ERRORLEVEL% NEQ 0 goto:build_error || EXIT /B 1
signtool verify /all /kp /v %DOKAN_PATH%\\Win32\\Win10Release\\dokan1.sys | find "Issued to: Microsoft Windows Hardware Compatibility Publisher"
IF %ERRORLEVEL% NEQ 0 goto:build_error || EXIT /B 1
%UNARCHIVE_COMMAND% %DOKAN_PATH%\\dokan_wix\\bin\\x64\\release\\Dokan_x64.msi Win10_Sys
IF %ERRORLEVEL% NEQ 0 goto:build_error || EXIT /B 1
signtool verify /all /kp /v Win10_Sys | find "Issued to: Microsoft Windows Hardware Compatibility Publisher"
IF %ERRORLEVEL% NEQ 0 goto:build_error || EXIT /B 1
%UNARCHIVE_COMMAND% %DOKAN_PATH%\\dokan_wix\\bin\\x86\\release\\Dokan_x86.msi Win10_Sys
IF %ERRORLEVEL% NEQ 0 goto:build_error || EXIT /B 1
signtool verify /all /kp /v Win10_Sys | find "Issued to: Microsoft Windows Hardware Compatibility Publisher"
IF %ERRORLEVEL% NEQ 0 goto:build_error || EXIT /B 1

:donecheckingdrivers

:: NOTE: We depend on the bot or caller to checkout client first
:: call:checkout_keybase client, %ClientRevision% || goto:build_error || EXIT /B 1
call:checkout_keybase kbfs, %KBFSRevision% || goto:build_error || EXIT /B 1
call:checkout_keybase go-updater, %UpdaterRevision% || goto:build_error || EXIT /B 1
call:checkout_keybase release, %ReleaseRevision% || goto:build_error || EXIT /B 1

::wait for CI
if [%UpdateChannel%] == [SmokeCI] call:check_ci  || EXIT /B 1

:done_ci

for /F delims^=^"^ tokens^=2 %%x in ('findstr /C:"Version = " %GOPATH%\src\github.com\keybase\client\go\libkb\version.go') do set LIBKB_VER=%%x

:: release
pushd %GOPATH%\src\github.com\keybase\release
del release.exe
go build
IF %ERRORLEVEL% NEQ 0 (
  goto:build_error || EXIT /B 1
)
for /f %%i in ('release winbuildnumber --version=%LIBKB_VER%') do set BUILD_NUMBER=%%i
echo %BUILD_NUMBER%
popd

if NOT DEFINED BUILD_NUMBER (
  echo bad build number
  goto:build_error || EXIT /B 1
)
:: ensure it's numeric
SET "badbuildnumber="&for /f "delims=0123456789" %%i in ("%BUILD_NUMBER%") do set badbuildnumber=%%i
if defined badbuildnumber (
  echo bad build number
  goto:build_error || EXIT /B 1
)

call %GOPATH%\src\github.com\keybase\client\packaging\windows\build_prerelease.cmd || goto:build_error || EXIT /B 1

::RunQuiet Utility
pushd %GOPATH%\src\github.com\keybase\client\go\tools\runquiet
del rq.hash
del old.hash
powershell -command "wget https://s3.amazonaws.com/prerelease.keybase.io/windows-support/runquiet/runquiet.hash -OutFile old.hash"
git log -1 -- runquiet.go > rq.hash
fc rq.hash old.hash
if %ERRORLEVEL% EQU 0 (
    echo "downloading keybaserq"
    powershell -command "wget https://s3.amazonaws.com/prerelease.keybase.io/windows-support/runquiet/keybaserq.exe -OutFile keybaserq.exe"
) else (
    echo "--- runquiet hashes differ, building keybaserq. Server hash: ---"
    type old.hash
    echo "--- Current hash: ---"
    type rq.hash
    call ..\..\..\packaging\windows\buildrq.bat || goto:build_error || EXIT /B 1
)
popd

call %GOPATH%\src\github.com\keybase\client\packaging\windows\buildui.bat || goto:build_error || EXIT /B 1

::Build Installer
call %GOPATH%\src\github.com\keybase\client\packaging\windows\doinstaller_wix.cmd || goto:build_error || EXIT /B 1

::Publish to S3
if %UpdateChannel% NEQ "None" (
    echo "Uploading %BUILD_TAG%"
    s3browser-con upload prerelease.keybase.io  %GOPATH%\src\github.com\keybase\client\packaging\windows\%BUILD_TAG%\Keybase_%BUILD_TAG%.386.exe prerelease.keybase.io/windows  || goto:build_error || EXIT /B 1
    :: Test channel json
    s3browser-con upload prerelease.keybase.io  %GOPATH%\src\github.com\keybase\client\packaging\windows\%BUILD_TAG%\update-windows-prod-test-v2.json prerelease.keybase.io || goto:build_error || EXIT /B 1
) else (
    echo "No update channel"
)

::Invoke SmokeB build
if [%UpdateChannel%] NEQ [Smoke] (
    if [%UpdateChannel%] NEQ [SmokeCI] (
        echo "Not a smoke build"
        goto :no_smokea
    )
)

:: Smoke A json
s3browser-con upload prerelease.keybase.io  %GOPATH%\src\github.com\keybase\client\packaging\windows\%BUILD_TAG%\*.json prerelease.keybase.io/windows-support || goto:build_error || EXIT /B 1

set PrevUpdateChannel=%UpdateChannel%
set UpdateChannel=Smoke2
set smokeASemVer=%KEYBASE_VERSION%
::SlackBot?

::build again
call %GOPATH%\src\github.com\keybase\client\packaging\windows\dorelease.cmd || EXIT /B 1

:: and we're done here

EXIT /B 0

:no_smokea

::Publish smoke updater jsons to S3
if [%UpdateChannel%] NEQ [Smoke2] (
    echo "Non Smoke2 build"
    %OUTPUT% "Successfully built Windows with client: %KEYBASE_VERSION%, kbfs: %KBFS_BUILD%"
    goto :no_smokeb
)
::Smoke B json
s3browser-con upload prerelease.keybase.io  %GOPATH%\src\github.com\keybase\client\packaging\windows\%BUILD_TAG%\*.json prerelease.keybase.io/windows-support  || goto:build_error || EXIT /B 1
set smokeBSemVer=%KEYBASE_VERSION%
%GOPATH%\src\github.com\keybase\release\release announce-build --build-a="%SmokeASemVer%" --build-b="%smokeBSemVer%" --platform="windows" || goto:build_error || EXIT /B 1
%OUTPUT% "Successfully built Windows: --build-a=%SmokeASemVer% --build-b=%smokeBSemVer%
:no_smokeb

echo %ERRORLEVEL%

goto:eof

:checkout_keybase

if EXIST %GOPATH%\src\github.com\keybase\%~1 goto:repoexists
pushd %GOPATH%\src\github.com\keybase
git clone https://github.com/keybase/%~1.git
popd
:repoexists

pushd %GOPATH%\src\github.com\keybase\%~1
git checkout master || EXIT /B 1
git pull || EXIT /B 1
git checkout %~2 || EXIT /B 1
popd
EXIT /B 0

goto:eof

:build_error
%OUTPUT% "Error building Windows"
EXIT /B 1

:check_ci
for /f %%i in ('git -C %GOPATH%\src\github.com\keybase\client rev-parse --short HEAD') do set clientCommit=%%i
for /f %%i in ('git -C %GOPATH%\src\github.com\keybase\kbfs rev-parse --short HEAD') do set kbfsCommit=%%i
echo [%clientCommit%] [%kbfsCommit%]
:: need GITHUB_TOKEN
pushd %GOPATH%\src\github.com\keybase\release
go build || goto:build_error || EXIT /B 1
release wait-ci --repo="client" --commit="%clientCommit%" --context="continuous-integration/jenkins/branch" --context="ci/circleci"  || goto:ci_error
release wait-ci --repo="kbfs" --commit="%kbfsCommit%" --context="continuous-integration/jenkins/branch" --context="ci/circleci"  || goto:ci_error
popd
EXIT /B 0

:ci_error
%OUTPUT% "CI Failure building Windows"
EXIT /B 1

Revert "zanderz/ssss_2017.12.26"

Revert "zanderz/ssss_2017.12.26"

This reverts commit fa6ba8b82321eb1e756a8f59ea27244d5fa19c80.


copy "%RECIPE_DIR%\build.sh" .
set PREFIX=%PREFIX:\=/%
set BUILD_PREFIX=%BUILD_PREFIX:\=/%
set LIBRARY_PREFIX=%LIBRARY_PREFIX:\=/%
set SRC_DIR=%SRC_DIR:\=/%
set MSYSTEM=MINGW%ARCH%
set MSYS2_PATH_TYPE=inherit
set CHERE_INVOKING=1

copy %LIBRARY_LIB%\pthreads.lib %LIBRARY_LIB%\pthread.lib
copy %LIBRARY_LIB%\pthreads.lib %LIBRARY_LIB%\m.lib
copy %BUILD_PREFIX%\Library\bin\llvm-ar.exe %BUILD_PREFIX%\Library\bin\ar.exe
copy %BUILD_PREFIX%\Library\bin\llvm-as.exe %BUILD_PREFIX%\Library\bin\as.exe

bash -lc "./build.sh"
if errorlevel 1 exit 1

del %LIBRARY_LIB%\pthread.lib
del %LIBRARY_LIB%\m.lib

opy %LIBRARY_LIB%\pthreads.lib %LIBRARY_LIB%\pthread.lib
copy %LIBRARY_LIB%\pthreads.lib %LIBRARY_LIB%\m.lib
copy %BUILD_PREFIX%\Library\bin\llvm-ar.exe %BUILD_PREFIX%\Library\bin\ar.exe
copy %BUILD_PREFIX%\Library\bin\llvm-as.exe %BUILD_PREFIX%\Library\bin\as.exe

copy "%RECIPE_DIR%\build.sh" .
set PREFIX=%PREFIX:\=/%
set BUILD_PREFIX=%BUILD_PREFIX:\=/%
set LIBRARY_PREFIX=%LIBRARY_PREFIX:\=/%
set SRC_DIR=%SRC_DIR:\=/%
set MSYSTEM=MINGW%ARCH%
set MSYS2_PATH_TYPE=inherit
set CHERE_INVOKING=1
bash -lc "./build.sh"
if errorlevel 1 exit 1

del %LIBRARY_LIB%\pthread.lib
del %LIBRARY_LIB%\m.lib

Fix BUILD_PREFIX

Fix BUILD_PREFIX


@ECHO OFF
@SETLOCAL
@SETLOCAL ENABLEDELAYEDEXPANSION

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: Description:
::     This script is a convenience for building all the
::     flavors of codegen and the Canvas solution (all
::     platforms and configurations), all in one step. Runs
::     the tests as well.
::
:: Usage:
::     BuildAndTestAllConfigs.cmd [path]
::
::     where [path] is the absolute path to your
::     local Git repository. This parameter is optional.
::
::     If [path] is not specified, the script will infer
::     your Git repository path from its location (works
::     so long as it hasn't been copied someplace else).
::
::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

WHERE /Q msbuild >NUL
IF %ERRORLEVEL% NEQ 0 (
    ECHO Error: It appears that 'msbuild' is not available in this environment.
    ECHO Please run this script from a Visual Studio command prompt, or
    ECHO ensure the PATH is configured correctly.
    GOTO END
)

IF "%1"=="/?" (
    ECHO Usage: %0 [path]
    ECHO    optional parameter [path] is the path to your local Git repository.
    ECHO    Example: BuildAndTestAllConfigs.cmd C:\Src
    GOTO END
)

SET ENABLE_PARALLEL=/m

SET BUILD_FLAGS=%ENABLE_PARALLEL%

SET GIT_TREE_LOCATION=%~dp0..\

IF NOT "%1"=="" (
   SET GIT_TREE_LOCATION=%1
)

set BIN_LOCATION=%GIT_TREE_LOCATION%\bin\

:: Codegen.sln
:: The codegen solution is intended to build on one platform, Any CPU.
for %%C in (Debug Release) DO (
    msbuild %GIT_TREE_LOCATION%\Codegen.sln %BUILD_FLAGS% /p:Configuration="%%C" /p:Platform="Any CPU"
    IF !ERRORLEVEL! NEQ 0 (
        ECHO.
        ECHO A build error occurred. Stopping at codegen.sln build, configuration %%C.
        GOTO END
    )

    SET TEST_BINARY_DIR=%BIN_LOCATION%\AnyCPU\%%C\codegen.test\
    SET TEST_BINARY_PATH=!TEST_BINARY_DIR!codegen.test.dll

    mstest /testcontainer:!TEST_BINARY_PATH!

    IF !ERRORLEVEL! NEQ 0 (
            ECHO.
            ECHO One or more tests have failed. Stopping at codegen.sln build, configuration %%C.
            GOTO END
    )
)

:: CANVAS.sln
:: TODO: Enable tests for this solution. The Canvas tests are a bit different from the codegen ones in that
:: they require being run in an AppContainer. See task #1053.
for %%P in (x86 x64 ARM) DO (
    for %%C in (Debug Release) DO (
        msbuild %GIT_TREE_LOCATION%\canvas.sln %BUILD_FLAGS% /p:Configuration="%%C" /p:Platform="%%P"
        IF !ERRORLEVEL! NEQ 0 (
            ECHO.
            ECHO A build error occurred. Stopping at canvas.sln build, configuration %%C, platform %%P.
            GOTO END
        )
    )
)

ECHO.
ECHO All builds succeeded. All tests succeeded.

:END

@ENDLOCAL

@ECHO OFF
@SETLOCAL
@SETLOCAL ENABLEDELAYEDEXPANSION

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: Description:
::     This script is a convenience for building all the
::     flavors of codegen and the Canvas solution (all
::     platforms and configurations), all in one step. Runs
::     the tests as well.
::
:: Usage:
::     BuildAndTestAllConfigs.cmd [path]
::
::     where [path] is the absolute path to your
::     local Git repository. This parameter is optional.
::
::     If [path] is not specified, the script will infer
::     your Git repository path from its location (works
::     so long as it hasn't been copied someplace else).
::
::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

WHERE /Q msbuild >NUL
IF %ERRORLEVEL% NEQ 0 (
    ECHO Error: It appears that 'msbuild' is not available in this environment.
    ECHO Please run this script from a Visual Studio command prompt, or
    ECHO ensure the PATH is configured correctly.
    GOTO END
)

IF "%1"=="/?" (
    ECHO Usage: %0 [path]
    ECHO    optional parameter [path] is the path to your local Git repository.
    ECHO    Example: BuildAndTestAllConfigs.cmd C:\Src
    GOTO END
)

SET ENABLE_PARALLEL=/m

SET BUILD_FLAGS=%ENABLE_PARALLEL%

SET GIT_TREE_LOCATION=%~dp0..\

IF NOT "%1"=="" (
   SET GIT_TREE_LOCATION=%1
)

set BIN_LOCATION=%GIT_TREE_LOCATION%\bin\

:: Codegen.sln
:: The codegen solution is intended to build on one platform, Any CPU.
for %%C in (Debug Release) DO (
    msbuild %GIT_TREE_LOCATION%\Codegen.sln %BUILD_FLAGS% /p:Configuration="%%C" /p:Platform="Any CPU"
    IF !ERRORLEVEL! NEQ 0 (
        ECHO.
        ECHO A build error occurred. Stopping at codegen.sln build, configuration %%C.
        GOTO END
    )

    SET TEST_BINARY_DIR=%BIN_LOCATION%\WindowsAnyCPU\%%C\codegen.test\
    SET TEST_BINARY_PATH=!TEST_BINARY_DIR!codegen.test.dll

    mstest /testcontainer:!TEST_BINARY_PATH!

    IF !ERRORLEVEL! NEQ 0 (
            ECHO.
            ECHO One or more tests have failed. Stopping at codegen.sln build, configuration %%C.
            GOTO END
    )
)

:: CANVAS.sln
:: TODO: Enable tests for this solution. The Canvas tests are a bit different from the codegen ones in that
:: they require being run in an AppContainer. See task #1053.
for %%P in (x86 x64 ARM) DO (
    for %%C in (Debug Release) DO (
        msbuild %GIT_TREE_LOCATION%\canvas.sln %BUILD_FLAGS% /p:Configuration="%%C" /p:Platform="%%P"
        IF !ERRORLEVEL! NEQ 0 (
            ECHO.
            ECHO A build error occurred. Stopping at canvas.sln build, configuration %%C, platform %%P.
            GOTO END
        )
    )
)

ECHO.
ECHO All builds succeeded. All tests succeeded.

:END

@ENDLOCAL

Update the test binary path referenced by the build script.


// 2>nul||@goto :batch
/*
:batch
@echo off
setlocal

:: find csc.exe
set "csc="
for /r "%SystemRoot%\Microsoft.NET\Framework\" %%# in ("*csc.exe") do  set "csc=%%#"

if not exist "%csc%" (
   echo no .net framework installed
   exit /b 10
)

if not exist "%~n0.exe" (
   call %csc% /nologo /r:"Microsoft.VisualBasic.dll" /out:"%~n0.exe" "%~dpsfnx0" || (
      exit /b %errorlevel%
   )
)
%~n0.exe %*
endlocal & exit /b %errorlevel%

*/

// reference
// https://stackoverflow.com/questions/462270/get-file-icon-used-by-shell
// https://www.bigfix.me/fixlet/details/21898
// https://gallery.technet.microsoft.com/scriptcenter/eeff544a-f690-4f6b-a586-11eea6fc5eb8

using System.Drawing;

class Class1
{
    public static void Main()
    {
        var filePath =  @"C:\Users\Public\Downloads\setup.exe";
        var theIcon = IconFromFilePath(filePath);

        if (theIcon != null)
        {
            // Save it to disk, or do whatever you want with it.
            using (var stream = new System.IO.FileStream(@filePath+".ico", System.IO.FileMode.CreateNew))
            {
                theIcon.Save(stream);
            }
        }
    }

    public static Icon IconFromFilePath(string filePath)
    {
        var result = (Icon)null;

        try
        {
            result = Icon.ExtractAssociatedIcon(filePath);
        }
        catch (System.Exception)
        {
            // swallow and return nothing. You could supply a default Icon here as well
        }

        return result;
    }
}

// 2>nul||@goto :batch
/*
:batch
@echo off
setlocal

:: find csc.exe
set "csc="
for /r "%SystemRoot%\Microsoft.NET\Framework\" %%# in ("*csc.exe") do  set "csc=%%#"

if not exist "%csc%" (
   echo no .net framework installed
   exit /b 10
)

if not exist "%~n0.exe" (
   call %csc% /nologo /r:"Microsoft.VisualBasic.dll" /out:"%~n0.exe" "%~dpsfnx0" || (
      exit /b %errorlevel%
   )
)
%~n0.exe %*
endlocal & exit /b %errorlevel%

*/

// reference
// https://stackoverflow.com/questions/462270/get-file-icon-used-by-shell
// https://www.bigfix.me/fixlet/details/21898
// https://gallery.technet.microsoft.com/scriptcenter/eeff544a-f690-4f6b-a586-11eea6fc5eb8

using System; // required by Console.WriteLine
using System.Drawing;

class Class1
{
    public static void Main( string[] args )
    {
        var filePath =  @"setup.exe";
        if (args.Length != 0)
        {
            filePath =  @args[0];
        }
        var theIcon = IconFromFilePath(filePath);

        if (theIcon != null)
        {
            // Save it to disk, or do whatever you want with it.
            using (var stream = new System.IO.FileStream(@filePath+".ico", System.IO.FileMode.CreateNew))
            {
                theIcon.Save(stream);
            }
        }
    }

    public static Icon IconFromFilePath(string filePath)
    {
        var result = (Icon)null;

        try
        {
            result = Icon.ExtractAssociatedIcon(filePath);
        }
        catch (System.Exception)
        {
            // swallow and return nothing. You could supply a default Icon here as well
            Console.WriteLine("ERROR: No Icon Found   TODO: Provide Default Icon?");
        }

        return result;
    }
}

Update ExtractAssociatedIcon.bat

Update ExtractAssociatedIcon.bat


@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"

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

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
    }
}

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 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 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( $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)
    Write-Verbose -Message ("$ $GO get -d " + $url)
    & $GO get -d $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 Build($version,$tags) {
    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
    $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 ".\nyagos.exe"
    }
    $env:GOARCH = $saveGOARCH
}

function Byte2DWord($a,$b,$c,$d){
    return ($a+256*($b+256*($c+256*$d)))
}

function Get-Architecture($bin){
    $addr = (Byte2DWord $bin[60] $bin[61] $bin[62] $bin[63])
    if( $bin[$addr] -eq 0x50 -and $bin[$addr+1] -eq 0x45 ){
        if( $bin[$addr+4] -eq 0x4C -and $bin[$addr+5 ] -eq 0x01 ){
            return 32
        }
        if( $bin[$addr+4] -eq 0x64 -and $bin[$addr+5] -eq 0x86 ){
            return 64
        }
    }
    return $null
}

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 Misc\version.txt) ""
        $env:GOARCH = $save
    }
    "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
        }
        Get-ChildItem "." -Recurse |
        Where-Object { $_.Name -eq "make.xml" } |
        ForEach-Object {
            $dir = (Split-Path $_.FullName -Parent)
            $xml = [xml](Get-Content $_.FullName)
            foreach($li in $xml.make.generate.li){
                if( -not $li ){ continue }
                foreach($target in $xml.make.generate.li.target){
                    if( -not $target ){ continue }
                    $path = (Join-Path $dir $target)
                    if( Test-Path $path ){
                        Do-Remove $path
                    }
                }
            }
        }

        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=([^\)"]+)' Misc\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 "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
        }
        Ask-Copy "_nyagos" $installDir
        try{
            Do-Copy nyagos.exe $installDir
        }catch{
            taskkill /F /im nyagos.exe
            try{
                Do-Copy nyagos.exe $installDir
            }catch{
                Write-Host "Could not update installed nyagos.exe"
                Write-Host "Some processes holds nyagos.exe now"
            }
            # [void]([System.Windows.Forms.MessageBox]::Show("Done"))
            timeout /T 3
        }
    }
    "get" {
        if( (git branch --contains) -eq "* master" ){
            Write-Verbose "$GO get -u -v ./..."
            & $GO get -u -v ./...
        } else {
            Write-Verbose "$GO get -v ./..."
            & $GO get -v ./...
        }
    }
    "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"

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

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
    }
}

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 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 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( $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)
    Write-Verbose -Message ("$ $GO get -d " + $url)
    & $GO get -d $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 Build($version,$tags) {
    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
    $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 ".\nyagos.exe"
    }
    $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 Misc\version.txt) ""
        $env:GOARCH = $save
    }
    "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
        }
        Get-ChildItem "." -Recurse |
        Where-Object { $_.Name -eq "make.xml" } |
        ForEach-Object {
            $dir = (Split-Path $_.FullName -Parent)
            $xml = [xml](Get-Content $_.FullName)
            foreach($li in $xml.make.generate.li){
                if( -not $li ){ continue }
                foreach($target in $xml.make.generate.li.target){
                    if( -not $target ){ continue }
                    $path = (Join-Path $dir $target)
                    if( Test-Path $path ){
                        Do-Remove $path
                    }
                }
            }
        }

        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=([^\)"]+)' Misc\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 "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
        }
        Ask-Copy "_nyagos" $installDir
        try{
            Do-Copy nyagos.exe $installDir
        }catch{
            taskkill /F /im nyagos.exe
            try{
                Do-Copy nyagos.exe $installDir
            }catch{
                Write-Host "Could not update installed nyagos.exe"
                Write-Host "Some processes holds nyagos.exe now"
            }
            # [void]([System.Windows.Forms.MessageBox]::Show("Done"))
            timeout /T 3
        }
    }
    "get" {
        if( (git branch --contains) -eq "* master" ){
            Write-Verbose "$GO get -u -v ./..."
            & $GO get -u -v ./...
        } else {
            Write-Verbose "$GO get -v ./..."
            & $GO get -v ./...
        }
    }
    "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:

remove Get-Architecture

make.cmd: remove Get-Architecture


@echo ON
setlocal enabledelayedexpansion

mkdir build
cd build
cmake -LAH                                                                          ^
    -DCMAKE_BUILD_TYPE="Release"                                                    ^
    -DCMAKE_PREFIX_PATH=${PREFIX}                                                   ^
    -DCMAKE_INSTALL_PREFIX=${PREFIX}                                                ^
    ..
if errorlevel 1 exit 1
cmake --build . --target install --config Release

Add Windows build

Add Windows build


REM Copyright 2015 Brian Smith.
REM Copyright 2016 Cory Benfield.
REM
REM Permission to use, copy, modify, and/or distribute this software for any
REM purpose with or without fee is hereby granted, provided that the above
REM copyright notice and this permission notice appear in all copies.
REM
REM THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
REM WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
REM MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
REM ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
REM WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
REM ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF

echo on
SetLocal EnableDelayedExpansion

REM This is the recommended way to choose the toolchain version, according to
REM Appveyor's documentation.
SET PATH=C:\Program Files (x86)\MSBuild\%TOOLCHAIN_VERSION%\Bin;%PATH%

set VCVARSALL="C:\Program Files (x86)\Microsoft Visual Studio %TOOLCHAIN_VERSION%\VC\vcvarsall.bat"

if [%Platform%] NEQ [x64] goto win32
set TARGET_ARCH=x86_64
set TARGET_PROGRAM_FILES=%ProgramFiles%
call %VCVARSALL% amd64
if %ERRORLEVEL% NEQ 0 exit 1
goto download

:win32
echo on
if [%Platform%] NEQ [Win32] exit 1
set TARGET_ARCH=i686
set TARGET_PROGRAM_FILES=%ProgramFiles(x86)%
call %VCVARSALL% amd64_x86
if %ERRORLEVEL% NEQ 0 exit 1
goto download

:download
REM vcvarsall turns echo off
echo on

REM Install Rust
set RUST_URL=https://static.rust-lang.org/dist/rust-%RUST%-%TARGET_ARCH%-pc-windows-msvc.msi
echo Downloading %RUST_URL%...
mkdir build
powershell -Command "(New-Object Net.WebClient).DownloadFile('%RUST_URL%', 'build\rust-%RUST%-%TARGET_ARCH%-pc-windows-msvc.msi')"
if %ERRORLEVEL% NEQ 0 (
  echo ...downloading failed.
  exit 1
)

start /wait msiexec /i build\rust-%RUST%-%TARGET_ARCH%-pc-windows-msvc.msi INSTALLDIR="%TARGET_PROGRAM_FILES%\Rust %RUST%" /quiet /qn /norestart
if %ERRORLEVEL% NEQ 0 exit 1

set PATH="%PYTHON%";"%PYTHON%\Scripts";"%TARGET_PROGRAM_FILES%\Rust %RUST%\bin";%PATH%

link /?
cl /?
rustc --version
cargo --version

python -m pip install -U setuptools pip wheel
if %ERRORLEVEL% NEQ 0 exit 1

python -m pip install -r test_requirements.txt
if %ERRORLEVEL% NEQ 0 exit 1

appveyor\build.cmd python -m pip install .
if %ERRORLEVEL% NEQ 0 exit 1

py.test test/
if %ERRORLEVEL% NEQ 0 exit 1

appveyor\build.cmd python setup.py bdist_wheel

REM Copyright 2015 Brian Smith.
REM Copyright 2016 Cory Benfield.
REM
REM Permission to use, copy, modify, and/or distribute this software for any
REM purpose with or without fee is hereby granted, provided that the above
REM copyright notice and this permission notice appear in all copies.
REM
REM THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
REM WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
REM MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
REM ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
REM WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
REM ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF

echo on
SetLocal EnableDelayedExpansion

REM This is the recommended way to choose the toolchain version, according to
REM Appveyor's documentation.
SET PATH=C:\Program Files (x86)\MSBuild\%TOOLCHAIN_VERSION%\Bin;%PATH%

set VCVARSALL="C:\Program Files (x86)\Microsoft Visual Studio %TOOLCHAIN_VERSION%\VC\vcvarsall.bat"

if [%Platform%] NEQ [x64] goto win32
set TARGET_ARCH=x86_64
set TARGET_PROGRAM_FILES=%ProgramFiles%
call %VCVARSALL% amd64
if %ERRORLEVEL% NEQ 0 exit 1
goto download

:win32
echo on
if [%Platform%] NEQ [Win32] exit 1
set TARGET_ARCH=i686
set TARGET_PROGRAM_FILES=%ProgramFiles(x86)%
call %VCVARSALL% amd64_x86
if %ERRORLEVEL% NEQ 0 exit 1
goto download

:download
REM vcvarsall turns echo off
echo on

REM Install Rust
set RUST_URL=https://static.rust-lang.org/dist/rust-%RUST%-%TARGET_ARCH%-pc-windows-msvc.msi
echo Downloading %RUST_URL%...
mkdir build
powershell -Command "(New-Object Net.WebClient).DownloadFile('%RUST_URL%', 'build\rust-%RUST%-%TARGET_ARCH%-pc-windows-msvc.msi')"
if %ERRORLEVEL% NEQ 0 (
  echo ...downloading failed.
  exit 1
)

start /wait msiexec /i build\rust-%RUST%-%TARGET_ARCH%-pc-windows-msvc.msi INSTALLDIR="%TARGET_PROGRAM_FILES%\Rust %RUST%" /quiet /qn /norestart
if %ERRORLEVEL% NEQ 0 exit 1

set PATH="%PYTHON%";"%PYTHON%\Scripts";"%TARGET_PROGRAM_FILES%\Rust %RUST%\bin";%PATH%

link /?
cl /?
rustc --version
cargo --version

python -m pip install -U setuptools pip wheel
if %ERRORLEVEL% NEQ 0 exit 1

python -m pip install -r test_requirements.txt
if %ERRORLEVEL% NEQ 0 exit 1

CALL appveyor\build.cmd python -m pip install .
if %ERRORLEVEL% NEQ 0 exit 1

py.test test/
if %ERRORLEVEL% NEQ 0 exit 1

CALL appveyor\build.cmd python setup.py bdist_wheel

Use the CALL command.

Use the CALL command.