$ScriptPath = Split-Path -Parent $MyInvocation.MyCommand.Definition

& "$ScriptPath\PowerShellProfile\Microsoft.PowerShell_profile.ps1"

## Developer Tools

choco install grepwin
choco install greenshot
choco install baretail

## choco install redis-64

## choco install virtualbox
## choco install vagrant

## choco install freeSSHD
## choco install Tunnelier

## choco install jenkins

## choco install rabbitmq

## choco install nginx

## choco install sqlite

## choco install mysql
## choco install postgresql

## choco install grails
## choco install scala

## choco install mongodb
## choco install mongovue

Add comment RE: redis-desktop-manager install

$ScriptPath = Split-Path -Parent $MyInvocation.MyCommand.Definition

& "$ScriptPath\PowerShellProfile\Microsoft.PowerShell_profile.ps1"

## Developer Tools

choco install grepwin
choco install greenshot
choco install baretail

## choco install redis-64
## choco install redis-desktop-manager

## choco install virtualbox
## choco install vagrant

## choco install freeSSHD
## choco install Tunnelier

## choco install jenkins

## choco install rabbitmq

## choco install nginx

## choco install sqlite

## choco install mysql
## choco install postgresql

## choco install grails
## choco install scala

## choco install mongodb
## choco install mongovue


get-childitem -recurse bin -Directory | remove-item -recurse
get-childitem -recurse obj -Directory | remove-item -recurse

$packages = join-path (get-location) "packages"
if (test-path $packages) { remove-item packages -recurse }

$version = get-content VERSION
$branch = git rev-parse --abbrev-ref HEAD
$hash = git log --pretty=format:%h -1
$suffix = "$branch.$hash"

dotnet publish -c Release -v m --version-suffix $suffix /p:versionprefix=$version /p:packageversion=$version
dotnet pack -o $packages -c release --no-build --version-suffix $suffix /p:versionprefix=$version /p:packageversion=$version

Allow specifying the version number

param ( [string] $Version, [string] $Configuration = "Release" )

get-childitem -recurse bin -Directory | remove-item -recurse
get-childitem -recurse obj -Directory | remove-item -recurse

$packages = join-path (get-location) "packages"
if (test-path $packages) { remove-item packages -recurse }

if ([String]::IsNullOrWhiteSpace($version)) { $version = get-content VERSION }

$branch = git rev-parse --abbrev-ref HEAD
$hash = git log --pretty=format:%h -1
$suffix = "$branch.$hash"

dotnet publish -c $Configuration -v n --version-suffix $suffix /p:versionprefix=$version /p:packageversion=$version
dotnet pack    -c $Configuration -v n --version-suffix $suffix /p:versionprefix=$version /p:packageversion=$version -o $packages --no-build


Add test for case insensitive query dictionary assembly

# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

Describe ".NET type with members with names differing only by name" {
    BeforeAll {
        Add-Type -TypeDefinition @'
namespace PSScriptAnalyzerTests
{
    public class QueryApiTestObject
    {
        public string JobId { get; set; }

        public object JOBID { get; set; }
    }
}
'@
    }

    It "Does not crash the query API" {
        $typeData = [Microsoft.PowerShell.CrossCompatibility.Utility.TypeDataConversion]::AssembleType([PSScriptAnalyzerTests.QueryApiTestObject])

        $typeQueryObject = New-Object 'Microsoft.PowerShell.CrossCompatibility.Query.TypeData' ('QueryApiTestObject', $typeData)

        $typeData.Instance.Properties.Count | Should -Be 1
        $typeData.Instance.Properties.Keys | Should -Contain 'jobid'
    }
}


. $PSScriptRoot\variables.ps1

$openCover = "c:\OpenCover\OpenCover.Console.exe"

$filter = '-filter:"+[GravatarHelper*]*'

Remove-Item $artifactDirectory\opencoverCoverage.xml

ForEach ($project in (Get-ChildItem -Path $testDirectory -File -Recurse -Filter *.csproj)) {
    $targetArgs = "-targetargs: test " + $project.FullName
    & $openCover -register:user -mergeoutput -output:$artifactDirectory\opencoverCoverage.xml -returntargetcode -target:"dotnet.exe" $targetArgs $filter
}

Verify the coverage artifact exists before attempting to delete it.

. $PSScriptRoot\variables.ps1

$openCover = "c:\OpenCover\OpenCover.Console.exe"

$filter = '-filter:"+[GravatarHelper*]*'

If (Test-Path $artifactDirectory\opencoverCoverage.xml) {
    Remove-Item $artifactDirectory\opencoverCoverage.xml
}

ForEach ($project in (Get-ChildItem -Path $testDirectory -File -Recurse -Filter *.csproj)) {
    $targetArgs = "-targetargs: test " + $project.FullName
    & $openCover -register:user -mergeoutput -output:$artifactDirectory\opencoverCoverage.xml -returntargetcode -target:"dotnet.exe" $targetArgs $filter
}


Write-Host "Installing chocolatey"
Set-ExecutionPolicy Unrestricted
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

Write-Host "Installing unzip"
choco install -y unzip

((New-Object System.Net.WebClient).DownloadFile('https://github.com/ctfhacker/windows-setup/archive/master.zip', 'C:\Windows\Temp\master.zip'))

cd C:\Windows\Temp\
unzip master.zip
cd windows-setup-master

Get-ChildItem | ForEach-Object {
    Write-Host "Executing " + $_.FullName
    & $_.FullName
}

Write-Host "Rebooting.."
shutdown /r /t 0

Use native powershell for unzipping

Write-Host "Installing chocolatey"
Set-ExecutionPolicy Unrestricted
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

((New-Object System.Net.WebClient).DownloadFile('https://github.com/ctfhacker/windows-setup/archive/master.zip', 'C:\Windows\Temp\master.zip'))

cd C:\Windows\Temp\
mkdir master
$shell = new-object -com shell.application
$zip = $shell.NameSpace("master.zip")
foreach($item in $zip.items())
{
    $shell.Namespace(".\master").copyhere($item)
}

cd master\windows-setup-master

Get-ChildItem | ForEach-Object {
    Write-Host "Executing " + $_.FullName
    & $_.FullName
}

Write-Host "Rebooting.."
shutdown /r /t 0


Describe "Select-XML DRT Unit Tests" -Tags DRT{
	$tmpDirectory = $TestDrive
	$testfilename = "testfile.xml"
	$testfile = Join-Path -Path $tmpDirectory -ChildPath $testfilename

	It "Select-XML should work"{
		$xmlContent = @"
<?xml version ="1.0" encoding="ISO-8859-1"?>
<bookstore>
	<book category="CHILDREN">
		<title lang="english">Harry Potter</title>
		<price>30.00</price>
	</book>
	<book category="WEB">
		<title lang="english">Learning XML</title>
		<price>25.00</price>
	</book>
</bookstore>
"@
		$xmlContent >$testfile
		try
		{
			$results=Select-XML -Path $testfile -XPath "/bookstore/book/title"
			$results.Count | Should Be 2
			$results[0].Node."#text" | Should Be "Harry Potter"
			$results[1].Node."#text" | Should Be "Learning XML"
		}
		finally
		{
			rm $testfile
		}
	}
}

Update fix based on comments for Select-XML Pester Test

Describe "Select-XML DRT Unit Tests" -Tags DRT{

	BeforeAll {
		$testfile = Join-Path -Path $TestDrive -ChildPath "testfile.xml"
		$xmlContent = @"
<?xml version ="1.0" encoding="ISO-8859-1"?>
<bookstore>
	<book category="CHILDREN">
		<title lang="english">Harry Potter</title>
		<price>30.00</price>
	</book>
	<book category="WEB">
		<title lang="english">Learning XML</title>
		<price>25.00</price>
	</book>
</bookstore>
"@
		$xmlContent >$testfile
	}
	AfterAll {
		rm $testfile
	}

	It "Select-XML should work"{
		$results = Select-XML -Path $testfile -XPath "/bookstore/book/title"
		$results.Count | Should Be 2
		$results[0].Node."#text" | Should Be "Harry Potter"
		$results[1].Node."#text" | Should Be "Learning XML"
	}
}


$rootPath = (Get-Item -Path ".\" -Verbose).FullName

dotnet restore

Set-Location 'src\Stranne.VasttrafikNET.Tests'

$resultsFile = $rootPath + '\artifacts\Stranne.VasttrafikNET_coverage.xml'
$openCoverConsole = $ENV:USERPROFILE + '\.nuget\packages\OpenCover\4.6.690\tools\OpenCover.Console.exe'
$target = '-target:C:\Program Files\dotnet\dotnet.exe'
$targetArgs = '-targetargs: test -c Release'
$filter = '-filter:+[Stranne.VasttrafikNET]* -[Stranne.VasttrafikNET.Tests]*'
$output = '-output:' + $resultsFile

& $openCoverConsole $target $targetArgs '-register:user' $filter '-hideskipped:Filter' '-returntargetcode' '-mergeoutput' $output '-oldStyle'

Set-Location $rootPath

$reportGenerator = $ENV:USERPROFILE + '\.nuget\packages\reportgenerator\2.5.6\tools\ReportGenerator.exe'
$reportOutput = $rootPath + '\artifacts\CoverageReport\'
$reports = '-reports:' + $resultsFile
$targetdir = '-targetdir:' + $reportOutput

If (Test-Path $reportOutput){
	Remove-Item $reportOutput -recurse
}

& $reportGenerator $reports $targetdir

Invoke-Item ($reportOutput + 'index.htm')

Remove any already existing coverage exports

$rootPath = (Get-Item -Path ".\" -Verbose).FullName

dotnet restore

Set-Location 'src\Stranne.VasttrafikNET.Tests'

$resultsFile = $rootPath + '\artifacts\Stranne.VasttrafikNET_coverage.xml'
If (Test-Path $resultsFile){
	Remove-Item $resultsFile
}

$openCoverConsole = $ENV:USERPROFILE + '\.nuget\packages\OpenCover\4.6.690\tools\OpenCover.Console.exe'
$target = '-target:C:\Program Files\dotnet\dotnet.exe'
$targetArgs = '-targetargs: test -c Release'
$filter = '-filter:+[Stranne.VasttrafikNET]* -[Stranne.VasttrafikNET.Tests]*'
$output = '-output:' + $resultsFile

& $openCoverConsole $target $targetArgs '-register:user' $filter '-hideskipped:Filter' '-returntargetcode' '-mergeoutput' $output '-oldStyle'

Set-Location $rootPath

$reportGenerator = $ENV:USERPROFILE + '\.nuget\packages\reportgenerator\2.5.6\tools\ReportGenerator.exe'
$reportOutput = $rootPath + '\artifacts\CoverageReport\'
$reports = '-reports:' + $resultsFile
$targetdir = '-targetdir:' + $reportOutput

If (Test-Path $reportOutput){
	Remove-Item $reportOutput -recurse
}

& $reportGenerator $reports $targetdir

Invoke-Item ($reportOutput + 'index.htm')


#region Initialize Cache
if (-not [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alert"]) {
	[Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alert"] = @{ }
}
#endregion Initialize Cache

#region Tepp Data return
$ScriptBlock = {
    param (
        $commandName,

        $parameterName,

        $wordToComplete,

        $commandAst,

        $fakeBoundParameter
    )

    $start = Get-Date
    [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Scripts["alert"].LastExecution = $start

	$server = $fakeBoundParameter['SqlInstance']

	if (-not $server) {
		$server = $fakeBoundParameter['Source']
	}

	if (-not $server) {
		$server = $fakeBoundParameter['ComputerName']
	}

	if (-not $server) { return }

    try
    {
        [DbaInstanceParameter]$parServer = $server | Select-Object -First 1
    }
    catch
    {
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Scripts["alert"].LastDuration = (Get-Date) - $start
        return
    }

    if ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alert"][$parServer.FullSmoName.ToLower()])
    {
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alert"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*"))
        {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Scripts["alert"].LastDuration = (Get-Date) - $start
        return
    }

    try
    {
        $serverObject = Connect-SqlInstance -SqlInstance $parServer -SqlCredential $fakeBoundParameter['SqlCredential'] -ErrorAction Stop
        foreach ($name in ([Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alert"][$parServer.FullSmoName.ToLower()] | Where-DbaObject -Like "$wordToComplete*"))
        {
            New-DbaTeppCompletionResult -CompletionText $name -ToolTip $name
        }
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Scripts["alert"].LastDuration = (Get-Date) - $start
        return
    }
    catch
    {
        [Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Scripts["alert"].LastDuration = (Get-Date) - $start
        return
    }
}

Register-DbaTeppScriptblock -ScriptBlock $ScriptBlock -Name alert
#endregion Tepp Data return

#region Update Cache
$ScriptBlock = {

	[Sqlcollaborative.Dbatools.TabExpansion.TabExpansionHost]::Cache["alert"][$FullSmoName] = $server.JobServer.Alerts.Name
}
Register-DbaTeppInstanceCacheBuilder -ScriptBlock $ScriptBlock
#endregion Update Cache


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

cd gr-release-develop

$env:GOPATH = $PWD
$env:PATH = $env:GOPATH + "/bin;C:/go/bin;" + $env:PATH

if ((Get-Command "go.exe" -ErrorAction SilentlyContinue) -eq $null) {
  Write-Host "Installing Go 1.9!"
  Invoke-WebRequest https://storage.googleapis.com/golang/go1.9.2.windows-amd64.msi -OutFile go.msi

  $p = Start-Process -FilePath "msiexec" -ArgumentList "/passive /norestart /i go.msi" -Wait -PassThru

  if($p.ExitCode -ne 0) {
    throw "Golang MSI installation process returned error code: $($p.ExitCode)"
  }

  Write-Host "Go is installed!"
}

go.exe build -o binary/gdn  code.cloudfoundry.org/guardian/cmd/gdn
if ($LASTEXITCODE -ne 0) {
    Write-Error "Error compiling: gdn"
}

Update golang to 1.9.3 in windows gqts

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

cd gr-release-develop

$env:GOPATH = $PWD
$env:PATH = $env:GOPATH + "/bin;C:/go/bin;" + $env:PATH

if ((Get-Command "go.exe" -ErrorAction SilentlyContinue) -eq $null) {
  Write-Host "Installing Go 1.9!"
  Invoke-WebRequest https://storage.googleapis.com/golang/go1.9.3.windows-amd64.msi -OutFile go.msi

  $p = Start-Process -FilePath "msiexec" -ArgumentList "/passive /norestart /i go.msi" -Wait -PassThru

  if($p.ExitCode -ne 0) {
    throw "Golang MSI installation process returned error code: $($p.ExitCode)"
  }

  Write-Host "Go is installed!"
}

go.exe build -o binary/gdn  code.cloudfoundry.org/guardian/cmd/gdn
if ($LASTEXITCODE -ne 0) {
    Write-Error "Error compiling: gdn"
}


function Add-Transformation($pattern, $values, $output){
$project = Get-Project
$buildProject =  @([Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($project.FullName))[0]
$afterBuildTarget= $buildProject.Xml.Targets | Where-Object {$_.Name -eq "AfterBuild"}
if($afterBuildTarget -eq $null)
{
	$afterBuildTarget = $buildProject.Xml.AddTarget("AfterBuild")
	Write-Host "Build target 'AfterBuild' has been created successfully."
}
$task = $afterBuildTarget.AddTask("VanillaTransformerTask")
$task.SetParameter("PatternFile", $pattern)
$task.SetParameter("ValuesSource", $values)
$task.SetParameter("OutputPath",$output)
$buildProject.Save()
$project.Save()
Write-Host "Transformation has been added successfully."
}

Add PS command to add transformation config to csproj

function Add-Transformation($pattern, $values, $output){
	$project = Get-Project
	$buildProject =  @([Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($project.FullName))[0]
	$afterBuildTarget= $buildProject.Xml.Targets | Where-Object {$_.Name -eq "AfterBuild"}
	if($afterBuildTarget -eq $null)
	{
		$afterBuildTarget = $buildProject.Xml.AddTarget("AfterBuild")
		Write-Host "Build target 'AfterBuild' has been created successfully."
	}
	$task = $afterBuildTarget.AddTask("VanillaTransformerTask")
	$task.SetParameter("PatternFile", $pattern)
	$task.SetParameter("ValuesSource", $values)
	$task.SetParameter("OutputPath",$output)
	$buildProject.Save()
	$project.Save()
	Write-Host "Transformation has been added successfully."
}

function Add-TransformationConfig($configFilePath){
	$project = Get-Project
	$buildProject =  @([Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($project.FullName))[0]
	$afterBuildTarget= $buildProject.Xml.Targets | Where-Object {$_.Name -eq "AfterBuild"}
	if($afterBuildTarget -eq $null)
	{
		$afterBuildTarget = $buildProject.Xml.AddTarget("AfterBuild")
		Write-Host "Build target 'AfterBuild' has been created successfully."
	}
	$task = $afterBuildTarget.AddTask("VanillaTransformerTask")
	$task.SetParameter("TransformConfiguration", $configFilePath)
	$buildProject.Save()
	$project.Save()
	Write-Host "Transformation configuration has been added successfully."
}


<#
.DESCRIPTION
    Swirch the physal director of an IIS Website.
#>
$WebAdministrationModule = 'WebAdministration'

If ( ! (Get-module $WebAdministrationModule )) {
    Write-Host "Loading module $WebAdministrationModule"
    Import-Module $WebAdministrationModule
}


Param(
    [switch] $Verbose
)

If (!$Verbose) {
    $quietFlag = '--quiet'
}
Else {
    $quietFlag = ''
}

$dnu = Get-Command dnu

& $dnu build 'src\HTTPlease*' 'test\HTTPlease*' $quietFlag

Hide non-zero exit code from dnu build.

Param(
    [switch] $Verbose
)

If (!$Verbose) {
    $quietFlag = '--quiet'
}
Else {
    $quietFlag = ''
}

$dnu = Get-Command dnu

& $dnu build 'src\HTTPlease*' 'test\HTTPlease*' $quietFlag

# Ugh - dnu build returns a non-zero exit code when building multiple projects, even if they all succeed.

Return 0


#requires -Version 3.0

$outputPath = "$PSScriptRoot\Distr"

Import-Module "$PSScriptRoot\Scripts\BuildHelpers.psm1"

Initialize-BuildVariables
Invoke-NugetRestore "$PSScriptRoot\DBVer.sln"

Invoke-SolutionBuild "$PSScriptRoot\DBVer.sln" 'Release'

if (Test-Path $outputPath)
{
    Remove-Item -recurse -force $outputPath
}

New-Item $outputPath -ItemType directory

$nugetExePath = "$PSScriptRoot\Scripts\nuget.exe"
$packagesPath = "$PSScriptRoot\packages"
&$nugetExePath install ILMerge -Version '2.14.1208' -OutputDirectory $packagesPath

$releasePath = "$PSScriptRoot\bin\Release"
$ilMergePath = $packagesPath + '\ilmerge.2.14.1208\tools\ILMerge.exe'

&$ilMergePath "/out:${outputPath}\DBVer.exe" "$releasePath\DBVer.exe" "$releasePath\*.dll" '/wildcards'

Copy-Item "$releasePath\DBVer.exe.config" $outputPath

Add distributive files to ZIP archive.

#requires -Version 3.0

$outputPath = "$PSScriptRoot\Distr"

Import-Module "$PSScriptRoot\Scripts\BuildHelpers.psm1"

Initialize-BuildVariables
Invoke-NugetRestore "$PSScriptRoot\DBVer.sln"

Invoke-SolutionBuild "$PSScriptRoot\DBVer.sln" 'Release'

if (Test-Path $outputPath)
{
    Remove-Item -recurse -force $outputPath
}

New-Item $outputPath -ItemType directory

$nugetExePath = "$PSScriptRoot\Scripts\nuget.exe"
$packagesPath = "$PSScriptRoot\packages"
&$nugetExePath install ILMerge -Version '2.14.1208' -OutputDirectory $packagesPath

$releasePath = "$PSScriptRoot\bin\Release"
$ilMergePath = $packagesPath + '\ilmerge.2.14.1208\tools\ILMerge.exe'

&$ilMergePath "/out:${outputPath}\DBVer.exe" "$releasePath\DBVer.exe" "$releasePath\*.dll" '/wildcards'

Copy-Item "$releasePath\DBVer.exe.config" $outputPath

&"${env:ProgramFiles}\7-Zip\7z.exe" a "$outputPath\DBVer0.0.0.zip" "$outputPath\*"


Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value '*'
$url = "https://raw.githubusercontent.com/MaxDistructo/ShellScripts/master/Comic%20Sans%20MS.reg"
$output = "c:\ComicSansMS.reg"
$wc = New-Object System.Net.WebClient
$wc.DownloadFile($url, $output)
reg.exe import C:\ComicSansMS.reg
Restart-Computer -Force

Allow local people and not all

Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value '172.18.*.*'
$url = "https://raw.githubusercontent.com/MaxDistructo/ShellScripts/master/Comic%20Sans%20MS.reg"
$output = "c:\ComicSansMS.reg"
$wc = New-Object System.Net.WebClient
$wc.DownloadFile($url, $output)
reg.exe import C:\ComicSansMS.reg
Restart-Computer -Force


#
# Set-UmbracoContinuousVersion
# Sets the Umbraco version for continuous integration
#
#   -Version <version>
#   where <version> is a Semver valid version
#   eg 1.2.3, 1.2.3-alpha, 1.2.3-alpha+456
#
#   -BuildNumber <buildNumber>
#   where <buildNumber> is an integer coming from the build server
#
function Set-UmbracoContinuousVersion
{
  param (
    [Parameter(Mandatory=$true)]
    [string]
    $version,
    [Parameter(Mandatory=$true)]
    [int]
    $buildNumber
  )

  $uenv = Get-UmbracoBuildEnv

  Write-Host "Version is currently set to $version"

  $versionComment = $buildNumber
  $versionComment = $versionComment.ToString().PadLeft(4,"0")
  $umbracoVersion = "$($version.Trim())-alpha$versionComment"

  Write-Host "Setting Umbraco Version to $umbracoVersion"
  Set-UmbracoVersion $umbracoVersion
}

Make VSTS responsible for padding the build number

#
# Set-UmbracoContinuousVersion
# Sets the Umbraco version for continuous integration
#
#   -Version <version>
#   where <version> is a Semver valid version
#   eg 1.2.3, 1.2.3-alpha, 1.2.3-alpha+456
#
#   -BuildNumber <buildNumber>
#   where <buildNumber> is a string coming from the build server
#   eg 34, 126, 1
#
function Set-UmbracoContinuousVersion
{
  param (
    [Parameter(Mandatory=$true)]
    [string]
    $version,
    [Parameter(Mandatory=$true)]
    [string]
    $buildNumber
  )

  Write-Host "Version is currently set to $version"

  $umbracoVersion = "$($version.Trim())-alpha$($buildNumber)"
  Write-Host "Setting Umbraco Version to $umbracoVersion"

  Set-UmbracoVersion $umbracoVersion
}


# Stop script execution when a non-terminating error occurs
$ErrorActionPreference = "Stop"

Write-Output "terminate-instance: waiting for 10 seconds to allow agent logs to drain to Cloudwatch..."
Start-Sleep -Seconds 10

$InstanceId = (Invoke-WebRequest -UseBasicParsing http://169.254.169.254/latest/meta-data/instance-id).content
$Region = (Invoke-WebRequest -UseBasicParsing http://169.254.169.254/latest/meta-data/placement/availability-zone).content -replace ".$"

Write-Output "terminate-instance: requesting instance termination..."
aws autoscaling terminate-instance-in-auto-scaling-group --region "$Region" --instance-id "$InstanceId" "--should-decrement-desired-capacity"

Add nssm stop signal if terminating

# Stop script execution when a non-terminating error occurs
$ErrorActionPreference = "Stop"

Write-Output "terminate-instance: waiting for 10 seconds to allow agent logs to drain to Cloudwatch..."
Start-Sleep -Seconds 10

$InstanceId = (Invoke-WebRequest -UseBasicParsing http://169.254.169.254/latest/meta-data/instance-id).content
$Region = (Invoke-WebRequest -UseBasicParsing http://169.254.169.254/latest/meta-data/placement/availability-zone).content -replace ".$"

Write-Output "terminate-instance: requesting instance termination..."
aws autoscaling terminate-instance-in-auto-scaling-group --region "$Region" --instance-id "$InstanceId" "--should-decrement-desired-capacity"

if ($lastexitcode -eq 0) { # If autoscaling request was successful, we will terminate
  Write-Output "terminate-instance: disabling buildkite-agent service"
  nssm stop buildkite-agent
}
else {
  Write-Output "terminate-instance: ASG could not decrement (we're already at minSize)"
}


if (!(Get-Command -Name dotnet -ErrorAction Ignore)) {
    Write-Verbose -Message (Get-DotFilesMessage -Message 'Skipping .NET Core settings as unable to locate dotnet.')
    return
}

Write-Verbose -Message (Get-DotFilesMessage -Message 'Loading .NET Core settings ...')

# Opt-out of telemetry
Set-Item -Path Env:\DOTNET_CLI_TELEMETRY_OPTOUT -Value 'true'

# Command completion for the dotnet CLI
# https://docs.microsoft.com/en-us/dotnet/core/tools/enable-tab-autocomplete
Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock {
    Param($CommandName, $WordToComplete, $CursorPosition)
    dotnet complete --position $CursorPosition, "$WordToComplete" | ForEach-Object {
        [Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
    }
}

Fix .NET Core completion support in PowerShell

if (!(Get-Command -Name dotnet -ErrorAction Ignore)) {
    Write-Verbose -Message (Get-DotFilesMessage -Message 'Skipping .NET Core settings as unable to locate dotnet.')
    return
}

Write-Verbose -Message (Get-DotFilesMessage -Message 'Loading .NET Core settings ...')

# Opt-out of telemetry
Set-Item -Path Env:\DOTNET_CLI_TELEMETRY_OPTOUT -Value 'true'

# How to enable TAB completion for the .NET Core CLI
# https://docs.microsoft.com/en-us/dotnet/core/tools/enable-tab-autocomplete
Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock {
    Param($wordToComplete, $commandAst, $cursorPosition)
    dotnet complete --position $cursorPosition "$commandAst" | ForEach-Object {
        [Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
    }
}


### Install handy tools and apps for my dev machine
### Run this script from an administrative shell

Set-ExecutionPolicy RemoteSigned

# Install Chocolatey
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Install some software with Chocolatey
choco install -y 7zip
choco install -y dotnetcore-sdk
choco install -y firacode
choco install -y git
choco install -y keepass
choco install -y linqpad
choco install -y nodejs-lts  # Remove if you plan to use Node Version Manager (see 2_download.ps1)
choco install -y notepadplusplus
choco install -y poshgit
choco install -y powershell-core --install-arguments='"ADDEXPLORERCONTEXTMENUOPENPOWERSHELL=1"'
choco install -y rdcman
choco install -y sql-server-management-studio
RefreshEnv.cmd

# Install some software with npm
npm install -g @angular/cli
npm install -g typescript

Install Git Credential Manager for Windows

### Install handy tools and apps for my dev machine
### Run this script from an administrative shell

Set-ExecutionPolicy RemoteSigned

# Install Chocolatey
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Install some software with Chocolatey
choco install -y 7zip
choco install -y dotnetcore-sdk
choco install -y firacode
choco install -y git
choco install -y git-credential-manager-for-windows
choco install -y keepass
choco install -y linqpad
choco install -y nodejs-lts  # Remove if you plan to use Node Version Manager (see 2_download.ps1)
choco install -y notepadplusplus
choco install -y poshgit
choco install -y powershell-core --install-arguments='"ADDEXPLORERCONTEXTMENUOPENPOWERSHELL=1"'
choco install -y rdcman
choco install -y sql-server-management-studio
RefreshEnv.cmd

# Install some software with npm
npm install -g @angular/cli
npm install -g typescript


$excel = new-object -comobject excel.application

$workbook = $excel.workbooks.open("Dinosaur.xlsm")
$worksheet = $workbook.worksheets.item(1)
$excel.Run("SortAndExport")
$workbook.save()
$workbook.close()

python "git version.py"

$excel.quit
pause

Add ability to have script in subfolder

$location = Get-Location
# Gets the path of the parent directory
$parent   = (get-item $location ).parent.FullName
$file     = "$parent\ExcelDino.xlsm"
$excel    = new-object -comobject excel.application

$workbook = $excel.workbooks.open($file)
$worksheet = $workbook.worksheets.item(1)
# Runs the macro that sorts and exports the excel file to .csv
$excel.Run("DinoSortExport")
$workbook.save()
$workbook.close()

python "../tiki-toki.py"

$excel.quit
pause


PowerShell -NoProfile -Command {
    $folder = 'C:\sources\serviceable-objects\Examples\TestHttpCompositionConsoleApp\bin\Debug\netcoreapp1.0';
    Set-Location -Path $folder;
    Import-Module "$folder\TestHttpCompositionConsoleApp.dll" -Verbose;

    #Get-Help Write-Message;
    Write-Message -Message "hey" -PipeName "container-X.service-X.testpipe" -NodeId "log-context";

    # Target examples:
    # Run-InstrumentationCommandOnCustomPipe -Pipe XXX -Data "hey" -OtherData "lo"
    # Run-InstrumentationCommandOnNode -Service XXX -ServiceContainer YYY -NodeId log-context -Data "hey" -OtherData "lo"
    # Do-SomethingOnServiceProcess -Service XXX -ServiceContainer YYY (add-node? merge-template? pause-service?, etc)
    # Do-SomethingOnServiceContainerProcess -ServiceContainer YYY (copy-service?, move-service?, update-service?, etc)

    Write-Host "Done.";
}

Revert script to generic format

$location = Split-Path $MyInvocation.MyCommand.Path;

PowerShell -NoProfile -Command {
    param (
        [String] $location
    )

    $folder = "$location\bin\Debug\netcoreapp1.0";
    Set-Location -Path $folder;
    Import-Module "$folder\TestHttpCompositionConsoleApp.dll" -Verbose;

    #Get-Help Write-Message;
    Write-Message -Message "hey" -PipeName "container-X.service-X.testpipe" -NodeId "log-context";

    # Target examples:
    # Run-InstrumentationCommandOnCustomPipe -Pipe XXX -Data "hey" -OtherData "lo"
    # Run-InstrumentationCommandOnNode -Service XXX -ServiceContainer YYY -NodeId log-context -Data "hey" -OtherData "lo"
    # Do-SomethingOnServiceProcess -Service XXX -ServiceContainer YYY (add-node? merge-template? pause-service?, etc)
    # Do-SomethingOnServiceContainerProcess -ServiceContainer YYY (copy-service?, move-service?, update-service?, etc)

    Write-Host "Done.";
} -args $location


if ($null -eq (Get-Command "docker.exe" -ErrorAction SilentlyContinue)) {
  Write-Error 'Docker cannot be found. Make sure it is installed and added to the path.'
  Start-Process -FilePath 'https://docs.docker.com/docker-for-windows/install/'
  continue;
}

docker build -t nunit-console-build .
docker run --rm -it -v ${PSScriptRoot}:/nunit-console -w=/nunit-console nunit-console-build bash build.sh $args

Revert the docker command trap

trap [Management.Automation.CommandNotFoundException] {
  Write-Error 'Docker cannot be found. Make sure it is installed and added to the path.'
  Start-Process -FilePath 'https://docs.docker.com/docker-for-windows/install/'
  continue;
}

docker build -t nunit-console-build .
docker run --rm -it -v ${PSScriptRoot}:/nunit-console -w=/nunit-console nunit-console-build bash build.sh $args


# Get and dot source all helper functions (private)
# Split-Path -Path $PSCommandPath |
#     Join-Path -ChildPath 'Helpers' |
#         Get-ChildItem -Include '*.ps1' -Exclude '*.Tests.*' -Recurse |
#             ForEach-Object { . $_.FullName }

# Get and dot source all external functions (public)
Split-Path -Path $PSCommandPath |
    Join-Path -ChildPath 'Functions' |
        Get-ChildItem -Include '*.ps1' -Exclude '*.Tests.*' -Recurse |
            ForEach-Object { . $_.FullName }

Update module, load helper functions

# Get and dot source all helper functions (private)
Split-Path -Path $PSCommandPath |
    Join-Path -ChildPath 'Helpers' |
        Get-ChildItem -Include '*.ps1' -Exclude '*.Tests.*' -Recurse |
            ForEach-Object { . $_.FullName }

# Get and dot source all external functions (public)
Split-Path -Path $PSCommandPath |
    Join-Path -ChildPath 'Functions' |
        Get-ChildItem -Include '*.ps1' -Exclude '*.Tests.*' -Recurse |
            ForEach-Object { . $_.FullName }


$packageName = "dotnet"
$installerType = "EXE"
$installerArgs = "/passive /norestart"
$url = "http://download.microsoft.com/download/E/2/1/E21644B5-2DF2-47C2-91BD-63C560427900/NDP452-KB2901907-x86-x64-AllOS-ENU.exe"

if ($psISE) {
    Import-Module -name "$env:ChocolateyInstall\chocolateyinstall\helpers\chocolateyInstaller.psm1"
    $ErrorActionPreference = "Stop"
}

try
{
    Install-ChocolateyPackage $packageName $installerType $installerArgs $url $url

    Write-ChocolateySuccess $packageName
}
catch
{
    Write-ChocolateyFailure $packageName $($_.Exception.Message)
    throw
}

Exit Code 3010 is ok as a exit code

$packageName = "dotnet"
$installerType = "EXE"
$installerArgs = "/passive /norestart"
$url = "http://download.microsoft.com/download/E/2/1/E21644B5-2DF2-47C2-91BD-63C560427900/NDP452-KB2901907-x86-x64-AllOS-ENU.exe"
$errorCode = @(0, 3010)

if ($psISE) {
    Import-Module -name "$env:ChocolateyInstall\chocolateyinstall\helpers\chocolateyInstaller.psm1"
    $ErrorActionPreference = "Stop"
}

try
{
    Install-ChocolateyPackage $packageName $installerType $installerArgs $url `
        -ValidExitCodes $errorCode

    Write-ChocolateySuccess $packageName
}
catch
{
    Write-ChocolateyFailure $packageName $($_.Exception.Message)
    throw
}


$AndroidToolPath = "${env:ProgramFiles(x86)}\Android\android-sdk\tools\android"
#$AndroidToolPath = "$env:localappdata\Android\android-sdk\tools\android"

Function Get-AndroidSDKs() {
    $output = & $AndroidToolPath list sdk --all
    $sdks = $output |% {
        if ($_ -match '(?<index>\d+)- (?<sdk>.+), revision (?<revision>[\d\.]+)') {
            $sdk = New-Object PSObject
            Add-Member -InputObject $sdk -MemberType NoteProperty -Name Index -Value $Matches.index
            Add-Member -InputObject $sdk -MemberType NoteProperty -Name Name -Value $Matches.sdk
            Add-Member -InputObject $sdk -MemberType NoteProperty -Name Revision -Value $Matches.revision
            $sdk
        }
    }
    $sdks
}

Function Install-AndroidSDK() {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true, Position=0)]
        [PSObject[]]$sdks
    )

    $sdkIndexes = $sdks |% { $_.Index }
    $sdkIndexArgument = [string]::Join(',', $sdkIndexes)
    Echo 'y' | & $AndroidToolPath update sdk -u -a -t $sdkIndexArgument
}

$sdks = Get-AndroidSDKs |? { $_.name -like 'sdk platform*API 15*' -or $_.name -like 'google apis*api 15' }
Install-AndroidSDK -sdks $sdks


$temp_directory = "$env:APPVEYOR_BUILD_FOLDER\Deploy\Portable\~TEMP"
New-Item "$temp_directory" -type directory

$zip_archive = "$env:APPVEYOR_BUILD_FOLDER\Deploy\Portable\Tabster $env:APPVEYOR_BUILD_VERSION Portable.exe"

& msbuild.exe "$env:APPVEYOR_BUILD_FOLDER\Tabster.sln" /p:Configuration=Portable

$output_directory = "$env:APPVEYOR_BUILD_FOLDER\Tabster\bin\Portable"

Copy-Item "$output_directory\*.exe" "$temp_directory"
Copy-Item "$output_directory\*.dll" "$temp_directory"
Copy-Item "$output_directory\*.config" "$temp_directory"
Copy-Item "$output_directory\*.config" "$temp_directory"

# copy subfolders recursively
Get-ChildItem -Path "$output_directory" -Recurse | ?{ $_.PSIsContainer } | copy-item -Destination "$temp_directory" -Force -Container

# move executable to project directory for clean AppVeyor artifact name
Move-Item "$zip_archive" "$env:APPVEYOR_BUILD_FOLDER"

Use 7z to zip contents

$temp_directory = "$env:APPVEYOR_BUILD_FOLDER\Deploy\Portable\~TEMP"
New-Item "$temp_directory" -type directory

$zip_archive = "$env:APPVEYOR_BUILD_FOLDER\Deploy\Portable\Tabster $env:APPVEYOR_BUILD_VERSION Portable.exe"

& msbuild.exe "$env:APPVEYOR_BUILD_FOLDER\Tabster.sln" /p:Configuration=Portable

$output_directory = "$env:APPVEYOR_BUILD_FOLDER\Tabster\bin\Portable"

Copy-Item "$output_directory\*.exe" "$temp_directory"
Copy-Item "$output_directory\*.dll" "$temp_directory"
Copy-Item "$output_directory\*.config" "$temp_directory"
Copy-Item "$output_directory\*.config" "$temp_directory"

# copy subfolders recursively
Get-ChildItem -Path "$output_directory" -Recurse | ?{ $_.PSIsContainer } | copy-item -Destination "$temp_directory" -Force -Container

& 7z a -r "$zip_archive" -mmt -mx5 -sfx7z.sfx "$temp_directory\*.*"

# move executable to project directory for clean AppVeyor artifact name
Move-Item "$zip_archive" "$env:APPVEYOR_BUILD_FOLDER"


Write-Host "mvn clean verify -DskipTests=true -P sonatype-oss-release"
mvn clean verify -DskipTests=true -P sonatype-oss-release

Write-Host "Packaging into bundle.jar..."
cd ./target
jar -cvf bundle.jar *.pom *.jar *.asc
Write-Host "Packaging into bundle.jar...DONE"

Read-Host "Press any key to exit..."


param (
    [Parameter(Mandatory=$true)][string]$apiKey
)

$branch = invoke-expression "git branch --show-current"

if ($branch -ne 'master') {
    Write-Error "Publishing only allowed from master branch"
    exit
}

$projPaths = @(
    "./AMT.Extensions.Logging",
    "./AMT.Extensions.System"
)

# Ensure everything is built
Write-Verbose "Pack projects"
$projPaths | %{
    write-host ""   # separator
    dotnet pack -c Release $_
}

# Publish to NuGet
Write-Verbose "Publish projects"
$projPaths | %{
    write-host ""   # separator
    $pkg = gci $_/bin/Release *.nupkg
    dotnet nuget push -k $apiKey $pkg.FullName -s https://api.nuget.org/v3/index.json
}


dotnet --version

$buildExitCode=0

Write-Output "*** Restoring packages"
dotnet restore
$buildExitCode = $LASTEXITCODE
if ($buildExitCode -ne 0){
    Write-Output "*** Restore failed"
    exit $buildExitCode
}

Write-Output "*** Building projects"
$buildExitCode=0
Get-Content build\build-order.txt | ForEach-Object {
   Write-Output "*** dotnet build $_"
    dotnet build $_
   if ($LASTEXITCODE -ne 0){
       $testExitCode = $LASTEXITCODE
   }
}
if($buildExitCode -ne 0) {
    Write-Output "*** Build failed"
    exit $buildExitCode
}

#$testExitCode = 0
#Get-Content build\test-order.txt | ForEach-Object {
#    dotnet test $_
#    if ($LASTEXITCODE -ne 0){
#        $testExitCode = $LASTEXITCODE
#    }
#}
#
#exit $testExitCode

Fix incorrect variable to track exit code

dotnet --version

$buildExitCode=0

Write-Output "*** Restoring packages"
dotnet restore
$buildExitCode = $LASTEXITCODE
if ($buildExitCode -ne 0){
    Write-Output "*** Restore failed"
    exit $buildExitCode
}

Write-Output "*** Building projects"
$buildExitCode=0
Get-Content build\build-order.txt | ForEach-Object {
   Write-Output "*** dotnet build $_"
    dotnet build $_
   if ($LASTEXITCODE -ne 0){
       $buildExitCode = $LASTEXITCODE
   }
}
if($buildExitCode -ne 0) {
    Write-Output "*** Build failed"
    exit $buildExitCode
}

#$testExitCode = 0
#Get-Content build\test-order.txt | ForEach-Object {
#    dotnet test $_
#    if ($LASTEXITCODE -ne 0){
#        $testExitCode = $LASTEXITCODE
#    }
#}
#
#exit $testExitCode


# You will need to make sure you have your C drive (or whatever drive you have the devopsdays code on) shared in Docker

$MyPath = $PSScriptRoot

docker stop hugo-server
docker rm hugo-server
docker run -p 1313:1313 -v ${MyPath}:/site --name hugo-server devopsdays/docker-hugo-server:v0.16

Update hugo docker powershell script for 0.18.1

# You will need to make sure you have your C drive (or whatever drive you have the devopsdays code on) shared in Docker

$MyPath = $PSScriptRoot

docker stop hugo-server
docker rm hugo-server
docker run -p 1313:1313 -v ${MyPath}:/site --name hugo-server devopsdays/docker-hugo-server:v0.18.1


$scenes = 'cornell-move-cone', 'sponza-hole', 'conference';
$ilpsolver = '..\x64\Debug\ILPSolver.exe';
$triesPerScene = 10;

foreach ($scene in $scenes) {
	for($i=1; $i -le $triesPerScene; $i++){
		$outLogFile = ".\examples\$scene-$i-log.txt";

		if(Test-Path $outLogFile){
			Write-Host $scene $i "Omitted";
			continue;
		}

		Write-Host $scene $i;
		Invoke-Expression "& $ilpsolver .\examples\$scene.xml";
		Move-Item ".\examples\log.txt" $outLogFile;
		Write-Host "Cooling down";
		Start-Sleep -s 10;
	}
}

Use conference simple on statistics

$scenes = 'cornell-move-cone', 'sponza-hole', 'conference-simple';
$ilpsolver = '..\x64\Debug\ILPSolver.exe';
$triesPerScene = 10;

foreach ($scene in $scenes) {
	for($i=1; $i -le $triesPerScene; $i++){
		$outLogFile = ".\examples\$scene-$i-log.txt";

		if(Test-Path $outLogFile){
			Write-Host $scene $i "Omitted";
			continue;
		}

		Write-Host $scene $i;
		Invoke-Expression "& $ilpsolver .\examples\$scene.xml";
		Move-Item ".\examples\log.txt" $outLogFile;
		Write-Host "Cooling down";
		Start-Sleep -s 10;
	}
}


#requires -v 3
param($cmd)

set-strictmode -off

. "$psscriptroot\..\lib\core.ps1"
. "$psscriptroot\..\lib\git.ps1"
. "$psscriptroot\..\lib\buckets.ps1"
. (relpath '..\lib\commands')

reset_aliases

$commands = commands
if (@('-v', '--version') -contains $args) {
    pushd $(versiondir 'scoop' 'current')
    write-host "Current Scoop version:"
    git_log --oneline HEAD -n 1
    write-host ""
    popd

    buckets | % {
        pushd $(bucketdir $_)
        if(test-path '.git') {
            write-host "'$_' bucket:"
            git_log --oneline HEAD -n 1
            write-host ""
        }
        popd
    }
}
elseif (@($null, '-h', '--help', '/?') -contains $cmd) { exec 'help' $args }
elseif ($commands -contains $cmd) { exec $cmd $args }
else { "scoop: '$cmd' isn't a scoop command. See 'scoop help'."; exit 1 }

Fix handling of -h and -v parameter

#requires -v 3
param($cmd)

set-strictmode -off

. "$psscriptroot\..\lib\core.ps1"
. "$psscriptroot\..\lib\git.ps1"
. "$psscriptroot\..\lib\buckets.ps1"
. (relpath '..\lib\commands')

reset_aliases

$commands = commands
if ('--version' -contains $cmd -or '-v' -contains $args ) {
    pushd $(versiondir 'scoop' 'current')
    write-host "Current Scoop version:"
    git_log --oneline HEAD -n 1
    write-host ""
    popd

    buckets | % {
        pushd $(bucketdir $_)
        if(test-path '.git') {
            write-host "'$_' bucket:"
            git_log --oneline HEAD -n 1
            write-host ""
        }
        popd
    }
}
elseif (@($null, '--help', '/?') -contains $cmd -or $args -contains '-h') { exec 'help' $args }
elseif ($commands -contains $cmd) { exec $cmd $args }
else { "scoop: '$cmd' isn't a scoop command. See 'scoop help'."; exit 1 }


"Updating docker engine"
docker version
"Stopping docker service"
stop-service docker
if (!(Test-Path C:\windows\system32\docker-orig.exe)) {
  "Saving docker original docker engine"
  copy-item C:\windows\system32\docker.exe C:\windows\system32\docker-orig.exe
}
"Downloading nightly build of docker engine"
wget https://master.dockerproject.org/windows/amd64/docker.exe -outfile C:\windows\system32\docker.exe
"Starting docker service"
start-service docker
docker version

Tag base images if latest tag is lost

"Updating docker engine"
docker version
"Stopping docker service"
stop-service docker
if (!(Test-Path C:\windows\system32\docker-orig.exe)) {
  "Saving docker original docker engine"
  copy-item C:\windows\system32\docker.exe C:\windows\system32\docker-orig.exe
}
"Downloading nightly build of docker engine"
wget https://master.dockerproject.org/windows/amd64/docker.exe -outfile C:\windows\system32\docker.exe
"Starting docker service"
start-service docker
if ("$(docker images windowsservercore:latest | wc -l)" -eq "1") {
  docker tag windowsservercore:10.0.10586.0 windowsservercore:latest
}
if ("$(docker images nanoserver:latest | wc -l)" -eq "1") {
  docker tag nanoserver:10.0.10586.0 nanoserver:latest
}
docker version


param (
    [Parameter(Mandatory=$true)][string]$manager,
    [Parameter(Mandatory=$true)][string]$user,
    [Parameter(Mandatory=$false)][string]$tenant
)

$passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
$password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))

[System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}

$managerUri="https://$manager/rest/"
$Global:SID
$authUri

$headers=@{'Content-Type'='application/json'}

try {
    if (!$tenant) {
        $authUri = $managerUri + "authentication/login/primary"
        }
    else {
        $authUri = $managerUri + "authentication/login"
        }

    $data = @{
        dsCredentials = @{
            password=$password
            userName=$user
            }
    }
    $requestbody = $data | ConvertTo-Json
    $requestbody
    $Global:SID=Invoke-RestMethod -Headers $headers -Method POST -Uri $authUri -Body $requestbody
}
catch {
    echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
    exit
}

Fix support for multi-tenant DSM

param (
    [Parameter(Mandatory=$true)][string]$manager,
    [Parameter(Mandatory=$true)][string]$user,
    [Parameter(Mandatory=$false)][string]$tenant
)

$passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
$password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))

[System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}

$managerUri="https://$manager/rest/"
$Global:SID
$authUri

$headers=@{'Content-Type'='application/json'}

try {
    $data = @{
        dsCredentials = @{
            password=$password
            userName=$user
            }
    }
    if (!$tenant) {
        $authUri = $managerUri + "authentication/login/primary"
        }
    else {
        $authUri = $managerUri + "authentication/login"
        $data.dsCredentials.Add("tenantName", $tenant)
        }

    $requestbody = $data | ConvertTo-Json
    $requestbody
    $Global:SID=Invoke-RestMethod -Headers $headers -Method POST -Uri $authUri -Body $requestbody
}
catch {
    echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
    exit
}


<#
.SYNOPSIS
    Parses parameters of the package

.EXAMPLE
    Get-PackageParameters "/Shortcut /InstallDir:'c:\program files\xyz' /NoStartup" | set r
    if ($r.Shortcut) {... }
    Write-Host $r.InstallDir

.OUTPUTS
    [HashTable]
#>
function Get-PackageParameters([string] $Parameters = $Env:ChocolateyPackageParameters) {
    $res = @{}
    $re = "\/([a-zA-Z]+)(:([`"'])?([a-zA-Z0-9- _\\:\.]+)([`"'])?)?"
    $results = $Parameters | Select-String $re -AllMatches | select -Expand Matches
    foreach ($m in $results) {
        if (!$m) { continue } # must because of posh 2.0 bug: https://github.com/chocolatey/chocolatey-coreteampackages/issues/465

        $a = $m.Value -split ':'
        $opt = $a[0].Substring(1); $val = $a[1..100] -join ':'
        if ($val -match '^(".+")|(''.+'')$') {$val = $val -replace '^.|.$'}
        $res[ $opt ] = if ($val) { $val } else { $true }
    }
    $res
}

Allow numbers in flag names

<#
.SYNOPSIS
    Parses parameters of the package

.EXAMPLE
    Get-PackageParameters "/Shortcut /InstallDir:'c:\program files\xyz' /NoStartup" | set r
    if ($r.Shortcut) {... }
    Write-Host $r.InstallDir

.OUTPUTS
    [HashTable]
#>
function Get-PackageParameters([string] $Parameters = $Env:ChocolateyPackageParameters) {
    $res = @{}
    write-host "p:  $Parameters"

    $re = "\/([a-zA-Z0-9]+)(:([`"'])?([a-zA-Z0-9- _\\:\.]+)([`"'])?)?"
    $results = $Parameters | Select-String $re -AllMatches | select -Expand Matches
    foreach ($m in $results) {
        if (!$m) { continue } # must because of posh 2.0 bug: https://github.com/chocolatey/chocolatey-coreteampackages/issues/465

        $a = $m.Value -split ':'
        $opt = $a[0].Substring(1); $val = $a[1..100] -join ':'
        if ($val -match '^(".+")|(''.+'')$') {$val = $val -replace '^.|.$'}
        $res[ $opt ] = if ($val) { $val } else { $true }
    }
    write-host $res
    $res
}


$regex = New-Object System.Text.RegularExpressions.Regex('<MajorVersion>(\d\.\d)</MajorVersion>')
$m = $regex.Match((Get-Content src\Salesforce.VisualStudio.Services\Salesforce.VisualStudio.Services.csproj))
$majorMinor = $m.Groups[1].Value
$version = $majorMinor + '.' + $env:BuildNumber

Add-AppveyorMessage -Message "Updating version to $version" -Category Information

Update-AppveyorBuild -Version $version

Fix appveyor version script to look at correct file.

$regex = New-Object System.Text.RegularExpressions.Regex('<MajorVersion>(\d\.\d)</MajorVersion>')
$m = $regex.Match((Get-Content Salesforce.props))
$majorMinor = $m.Groups[1].Value
$version = $majorMinor + '.' + $env:BuildNumber

Add-AppveyorMessage -Message "Updating version to $version" -Category Information

Update-AppveyorBuild -Version $version


git commit --amend
-avoid if you've already pushed
-change the commit message, or
-change the snapshot with `add` or `rm`
-warning: is a mini-rebase, changes the SHA

git rebase -i
-supply the parent of the last commit you want to edit


$packageName = 'Chocolatey Explorer'
$installerType = 'exe'
$url = 'http://chocolatey-explorer.jdibble.co.uk/setup.exe'
$silentArgs = '/i /s'
$validExitCodes = @(0)

Install-ChocolateyPackage "$packageName" "$installerType" "$silentArgs" "$url" -validExitCodes $validExitCodes

Use the application manifest in the Chocolatey package over the setup executable

$packageName = 'Chocolatey Explorer'
$installerType = 'exe'
$url = 'http://chocolatey-explorer.jdibble.co.uk/chocolatey-explorer.application'
$silentArgs = '/i /s'
$validExitCodes = @(0)

Install-ChocolateyPackage "$packageName" "$installerType" "$silentArgs" "$url" -validExitCodes $validExitCodes


Set-PSReadLineOption -EditMode "Vi" -Colors @{
  Command = [ConsoleColor]::White
  Comment = [ConsoleColor]::White
  ContinuationPrompt = [ConsoleColor]::White
  DefaultToken = [ConsoleColor]::White
  Emphasis = [ConsoleColor]::White
  Error = [ConsoleColor]::White
  Keyword = [ConsoleColor]::White
  Member = [ConsoleColor]::White
  Number = [ConsoleColor]::White
  Operator = [ConsoleColor]::White
  Parameter = [ConsoleColor]::White
  Selection = [ConsoleColor]::White
  String = [ConsoleColor]::White
  Type = [ConsoleColor]::White
  Variable = [ConsoleColor]::White
}

function prompt {
  Write-Host "┏╸" -ForegroundColor Magenta -NoNewLine
  Write-Host $pwd -ForegroundColor DarkYellow

  $branch = & git branch 2>out-null
  if ($branch -ne $null) {
    Set-PSReadLineOption -ExtraPromptLineCount 2
    Write-Host "┣╸" -ForegroundColor Magenta -NoNewLine
    Write-Host "<" -ForegroundColor DarkYellow -NoNewLine
    Write-Host $branch.SubString(2) -ForegroundColor Magenta -NoNewLine
    Write-Host ">" -ForegroundColor DarkYellow
  }
  else {
    Set-PSReadLineOption -ExtraPromptLineCount 1
    # Write-Host "┣╸" -ForegroundColor Magenta
  }

  Write-Host "┗" -ForegroundColor Magenta -NoNewLine
  "╸"
}

function awscli {
  Import-Module AWSPowerShell.NetCore
}

Enable Bash-Like Tab-Complete With Powershell

Set-PSReadLineOption -EditMode "Vi" -Colors @{
  Command = [ConsoleColor]::White
  Comment = [ConsoleColor]::White
  ContinuationPrompt = [ConsoleColor]::White
  DefaultToken = [ConsoleColor]::White
  Emphasis = [ConsoleColor]::White
  Error = [ConsoleColor]::White
  Keyword = [ConsoleColor]::White
  Member = [ConsoleColor]::White
  Number = [ConsoleColor]::White
  Operator = [ConsoleColor]::White
  Parameter = [ConsoleColor]::White
  Selection = [ConsoleColor]::White
  String = [ConsoleColor]::White
  Type = [ConsoleColor]::White
  Variable = [ConsoleColor]::White
}

Set-PSReadlineKeyHandler -Key Tab -Function Complete

function prompt {
  Write-Host "┏╸" -ForegroundColor Magenta -NoNewLine
  Write-Host $pwd -ForegroundColor DarkYellow

  $branch = & git branch 2>out-null
  if ($branch -ne $null) {
    Set-PSReadLineOption -ExtraPromptLineCount 2
    Write-Host "┣╸" -ForegroundColor Magenta -NoNewLine
    Write-Host "<" -ForegroundColor DarkYellow -NoNewLine
    Write-Host $branch.SubString(2) -ForegroundColor Magenta -NoNewLine
    Write-Host ">" -ForegroundColor DarkYellow
  }
  else {
    Set-PSReadLineOption -ExtraPromptLineCount 1
    # Write-Host "┣╸" -ForegroundColor Magenta
  }

  Write-Host "┗" -ForegroundColor Magenta -NoNewLine
  "╸"
}

function awscli {
  Import-Module AWSPowerShell.NetCore
}


[CmdletBinding(PositionalBinding=$false)]
param (
    [switch]$release = $false)

Set-StrictMode -version 2.0
$ErrorActionPreference = "Stop"

try {
    . (Join-Path $PSScriptRoot "build-utils.ps1")
    Push-Location $repoDir

    Write-Host "Repo Dir $repoDir"
    Write-Host "Binaries Dir $binariesDir"

    $buildConfiguration = if ($release) { "Release" } else { "Debug" }
    $configDir = Join-Path (Join-Path $binariesDir "VSSetup") $buildConfiguration

    $optProfToolDir = Get-PackageDir "Roslyn.OptProf.RunSettings.Generator"
    $optProfToolExe = Join-Path $optProfToolDir "tools\roslyn.optprof.runsettings.generator.exe"
    $configFile = Join-Path $repoDir "build\config\optprof.json"
    $outputFolder = Join-Path $configDir "Insertion\RunSettings"
    $optProfArgs = "--configFile $configFile --outputFolder $outputFolder --buildNumber 28302.01 "

    Exec-Console $optProfToolExe $optProfArgs
    exit 0
}
catch {
    Write-Host $_
    Write-Host $_.Exception
    Write-Host $_.ScriptStackTrace
    exit 1
}
finally {
    Pop-Location
}

Use RepoRoot instead of repoDir

[CmdletBinding(PositionalBinding=$false)]
param (
    [switch]$release = $false)

Set-StrictMode -version 2.0
$ErrorActionPreference = "Stop"

try {
    . (Join-Path $PSScriptRoot "build-utils.ps1")
    Push-Location $RepoRoot

    Write-Host "Repo Dir $RepoRoot"
    Write-Host "Binaries Dir $binariesDir"

    $buildConfiguration = if ($release) { "Release" } else { "Debug" }
    $configDir = Join-Path (Join-Path $binariesDir "VSSetup") $buildConfiguration

    $optProfToolDir = Get-PackageDir "Roslyn.OptProf.RunSettings.Generator"
    $optProfToolExe = Join-Path $optProfToolDir "tools\roslyn.optprof.runsettings.generator.exe"
    $configFile = Join-Path $RepoRoot "build\config\optprof.json"
    $outputFolder = Join-Path $configDir "Insertion\RunSettings"
    $optProfArgs = "--configFile $configFile --outputFolder $outputFolder --buildNumber 28302.01 "

    Exec-Console $optProfToolExe $optProfArgs
    exit 0
}
catch {
    Write-Host $_
    Write-Host $_.Exception
    Write-Host $_.ScriptStackTrace
    exit 1
}
finally {
    Pop-Location
}


param($username, $password, [switch]$Buildserver)

$PSScriptRoot = split-path -parent $MyInvocation.MyCommand.Definition

$module = "Keith"

Import-Module "$PSScriptRoot\src\$module" -Force

New-PsDoc -Module $module -Path "$PSScriptRoot\docs\" -OutputLocation "$PSScriptRoot\docs-generated"

New-GitBook "$PSScriptRoot\docs-generated" "$PSScriptRoot\temp" $username $password -Buildserver:$Buildserver

Remove auth params for doc generation Authentication and repo management should be moved to another script...


$ErrorActionPreference = 'Stop';
$toolsDir   = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$url64      = 'https://certifytheweb.s3.amazonaws.com/downloads/CertifyTheWebSetup.exe'

$packageArgs = @{
  packageName   = $env:ChocolateyPackageName
  unzipLocation = $toolsDir
  fileType      = 'exe'
  url64bit      = $url64
  softwareName  = 'Certify The Web*'
  checksum64    = '0578b907488eb426060ce6a098f0d4da8e533ae49b47f18193efbab81fa965bd'
  checksumType64= 'sha256'
  validExitCodes= @(0)
  silentArgs   = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-'
}

Install-ChocolateyPackage @packageArgs

Fix hash for chocolate package install

$ErrorActionPreference = 'Stop';
$toolsDir   = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$url64      = 'https://certifytheweb.s3.amazonaws.com/downloads/CertifyTheWebSetup.exe'

$packageArgs = @{
  packageName   = $env:ChocolateyPackageName
  unzipLocation = $toolsDir
  fileType      = 'exe'
  url64bit      = $url64
  softwareName  = 'Certify The Web*'
  checksum64    = '417af6e1ea83c7180166590b753a3111e6410327273eb402b3782be951598576'
  checksumType64= 'sha256'
  validExitCodes= @(0)
  silentArgs   = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-'
}

Install-ChocolateyPackage @packageArgs


if (($env:appveyor_repo_tag -eq "True") -and ($env:appveyor_repo_branch.StartsWith("v"))) {
    write-output "Deploying to PyPI..."
    Invoke-Expression "twine upload -u mcflugen -p $env:PYPI_PASS dist/*"
    write-output "OK"
} else {
    write-output "Not deploying."
    write-output "Repo tag is $env:appveyor_repo_tag"
    write-output "Branch name $env:appveyor_repo_branch"
}

Check tag name to determine if it's time to deploy.

if (($env:appveyor_repo_tag -eq "true") -and ($env:appveyor_repo_tag_name.StartsWith("v"))) {
    write-output "Deploying to PyPI..."
    Invoke-Expression "twine upload -u mcflugen -p $env:PYPI_PASS dist/*"
    write-output "OK"
} else {
    write-output "Not deploying."
    write-output "Repo tag is $env:appveyor_repo_tag"
    write-output "Branch name $env:appveyor_repo_tag_name"
}


param
(
    $Path = "C:\telepresence"
)

echo "Installing telepresence to $Path"

Start-Process msiexec -Wait -verb runAs -Args "/i $current_directory\winfsp.msi /passive /qn /L*V winfsp-install.log"
Start-Process msiexec -Wait -verb runAs -Args "/i $current_directory\sshfs-win.msi /passive /qn /L*V sshfs-win-install.log"

if(!(test-path $Path))
{
    New-Item -ItemType Directory -Force -Path $Path
}

Copy-Item "telepresence.exe" -Destination "$Path" -Force
Copy-Item "wintun.dll" -Destination "$Path" -Force

# We update the PATH to include telepresence and its dependency, sshfs-win
[Environment]::SetEnvironmentVariable("Path", "C:\$Path;C:\\Program Files\\SSHFS-Win\\bin;$ENV:Path")

Fix windows install script to set Path for the user

param
(
    $Path = "C:\telepresence"
)

echo "Installing telepresence to $Path"

Start-Process msiexec -Wait -verb runAs -Args "/i $current_directory\winfsp.msi /passive /qn /L*V winfsp-install.log"
Start-Process msiexec -Wait -verb runAs -Args "/i $current_directory\sshfs-win.msi /passive /qn /L*V sshfs-win-install.log"

if(!(test-path $Path))
{
    New-Item -ItemType Directory -Force -Path $Path
}

Copy-Item "telepresence.exe" -Destination "$Path" -Force
Copy-Item "wintun.dll" -Destination "$Path" -Force

# We update the PATH to include telepresence and its dependency, sshfs-win
[Environment]::SetEnvironmentVariable("Path", "$Path;C:\Program Files\SSHFS-Win\bin;$ENV:Path", "Machine")


# Tests related to TFS item 1370133 [PSUpgrade] Need -NoNewline parameter on Out-File, Add-Content and Set-Content
# Connect request https://connect.microsoft.com/PowerShell/feedback/details/524739/need-nonewline-parameter-on-out-file-add-content-and-set-content

Describe "Tests for -NoNewline parameter of Out-File, Add-Content and Set-Content" -tags "Feature" {

    It "NoNewline parameter works on Out-File" {
         $temp = New-TemporaryFile
         1..5 | Out-File $temp.FullName -Encoding 'ASCII' -NoNewline
         (Get-Content $temp -Encoding Byte).Count | Should Be 5
         Remove-Item $temp -ErrorAction SilentlyContinue -Force
    }

    It "NoNewline parameter works on Set-Content" {
         $temp = New-TemporaryFile
         Set-Content -Path $temp.FullName -Value 'a','b','c' -Encoding 'ASCII' -NoNewline
         (Get-Content $temp -Encoding Byte).Count | Should Be 3
         Remove-Item $temp -ErrorAction SilentlyContinue -Force
    }

    It "NoNewline parameter works on Add-Content" {
         $temp = New-TemporaryFile
         1..9 | %{Add-Content -Path $temp.FullName -Value $_ -Encoding 'ASCII' -NoNewline}
         (Get-Content $temp -Encoding Byte).Count | Should Be 9
         Remove-Item $temp -ErrorAction SilentlyContinue -Force
    }
}

Rewrite to use $TESTDRIVE which does auto cleanup

# Tests related to TFS item 1370133 [PSUpgrade] Need -NoNewline parameter on Out-File, Add-Content and Set-Content
# Connect request https://connect.microsoft.com/PowerShell/feedback/details/524739/need-nonewline-parameter-on-out-file-add-content-and-set-content

Describe "Tests for -NoNewline parameter of Out-File, Add-Content and Set-Content" -tags "Feature" {

    It "NoNewline parameter works on Out-File" {
         $temp = "${TESTDRIVE}/test1.txt"
         1..5 | Out-File $temp -Encoding 'ASCII' -NoNewline
         (Get-Content $temp -Encoding Byte).Count | Should Be 5
    }

    It "NoNewline parameter works on Set-Content" {
         $temp = "${TESTDRIVE}/test2.txt"
         Set-Content -Path $temp -Value 'a','b','c' -Encoding 'ASCII' -NoNewline
         (Get-Content $temp -Encoding Byte).Count | Should Be 3
    }

    It "NoNewline parameter works on Add-Content" {
         $temp = "${TESTDRIVE}/test3.txt"
         $temp = New-TemporaryFile
         1..9 | %{Add-Content -Path $temp -Value $_ -Encoding 'ASCII' -NoNewline}
         (Get-Content $temp -Encoding Byte).Count | Should Be 9
    }
}


# params
$location = "LOCATION"
$ResourceGroupName = "GEN-KEYVAULT-RESOURCEGROUP-NAM"
$KeyVaultName = "GEN-KEYVAULT-NAME"
$KeyName = "GEN-KEYVAULT-ENCRYPTION-KEY"

#Connect to your Azure account
# Add-AzureAccount

#Select your subscription if you have more than one
# Select-AzureSubscription -SubscriptionName "My Subscription Name"

# Create a new Key vault, with enable soft delete (prerequisites to use a stored key as encryption protector for SQL)
New-AzureRmKeyVault -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName -Location $location -EnableSoftDelete

# Generate a key
Add-AzureKeyVaultKey -VaultName $KeyVaultName -Name $KeyName -Destination 'Software'

Update of the powershell script

function New-KeyVaultAndKey()
{
     #<#
	#.Synopsis
	#	   Deploy a new Key Vault and add a key that will be used as encryption protector for Azure SQL Server
	#.Description
    #      Use this script if you do not have already a Key Vault - otherwise, you can use yours in the ARM template included in this repo
    #
	#.Parameter SubscriptionId
    #      SubscriptionId is the identifier of the subscription to use.
	#.Parameter ResourceGroupName
    #      Azure resource group name. If this resource group exists, it will be used for the new Key Vault deployment
    #.Parameter KeyVaultLocation
    #      Azure Key Vault deployment location
    #.Parameter KeyVaultName
    #      Azure Key Vault name to deploy
    #.Parameter KeyName
    #      Azure Key Vault key name to insert in the Azure Key Vault
	##>
    param
    (
      [Parameter(Mandatory)]
      [string]$SubscriptionId,

      [Parameter(Mandatory)]
      [string]$ResourceGroupName,

      [Parameter(Mandatory)]
      [string]$KeyVaultLocation,

      [Parameter(Mandatory)]
      [string]$KeyVaultName,

      [Parameter(Mandatory)]
      [string]$KeyName
    )

    Add-AzureRmAccount

    Write-Host 'Selecting Azure Subscription...' $SubscriptionId -foregroundcolor Yellow
    Select-AzureRmSubscription -SubscriptionId $SubscriptionId

    # Create a new Key vault, with enable soft delete (prerequisites to use a stored key as encryption protector for SQL)
    Write-Host 'Creating the new Key Vault...' -foregroundcolor Yellow
    New-AzureRmKeyVault -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName -Location $KeyVaultLocation -EnableSoftDelete

    # Generate a key
    Write-Host 'Adding the new key inside the Key Vault...' -foregroundcolor Yellow
    Add-AzureKeyVaultKey -VaultName $KeyVaultName -Name $KeyName -Destination 'Software'
}


[OutputType([void])]
param(
	[Parameter()]
	$config = "Release"
)

Remove-Item *.nupkg

$nuspecFiles = get-childitem FubarDev.FtpServer*\*.nuspec
ForEach ($nuspecFile in $nuspecFiles)
{
	$csFile = [System.IO.Path]::ChangeExtension($nuspecFile, ".csproj")
	& nuget pack "$csFile" -Properties "Configuration=$config" -IncludeReferencedProjects
}

Fix for missing package version due to an non-working meta data extractor

[OutputType([void])]
param(
	[Parameter()]
	$version = "1.0.0-beta20",
	[Parameter()]
	$config = "Release"
)

Remove-Item *.nupkg

$nuspecFiles = get-childitem FubarDev.FtpServer*\*.nuspec
ForEach ($nuspecFile in $nuspecFiles)
{
	$csFile = [System.IO.Path]::ChangeExtension($nuspecFile, ".csproj")
	& nuget pack "$csFile" -Properties "Configuration=$config;Version=$version" -IncludeReferencedProjects
}


# Use the Git and posh-git from GitHub for Windows.
# See <http://stackoverflow.com/a/12524788>
. (Resolve-Path "$env:LOCALAPPDATA\GitHub\shell.ps1")
. $env:github_posh_git\profile.example.ps1

Import-Module PSReadLine
Set-PSReadlineOption -EditMode Emacs

Add 'converge' alias for running chef-client.

# Use the Git and posh-git from GitHub for Windows.
# See <http://stackoverflow.com/a/12524788>
. (Resolve-Path "$env:LOCALAPPDATA\GitHub\shell.ps1")
. $env:github_posh_git\profile.example.ps1

Import-Module PSReadLine
Set-PSReadlineOption -EditMode Emacs

# Shortcut for running chef-client. '-A' makes chef-client fail out if
# not run as administrator.
function converge {
	chef-client -A
}


# Powershell script to pull the VM files from GitHub into the current folder.
# Edit the following to match the version of the VM that is compatible with this image

param
(
    [string]$VMversion="v7.0.30"
)

Try
{
	$scriptDir = Split-Path $script:MyInvocation.MyCommand.Path;
	Write-Host "Fetching DolphinVM.zip" $VMversion
	$source = "https://github.com/dolphinsmalltalk/DolphinVM/releases/download/$VMversion/DolphinVM.zip";
	$zipFile = $scriptDir+"\DolphinVM.zip";
	Invoke-WebRequest $source -OutFile $zipFile;
}
Catch
{
	Write-Host "Unable to fetch DolphinVM.zip" $VMversion;
	Break;
}

$shell = new-object -com shell.application;
$zip = $shell.NameSpace($zipFile);
foreach($item in $zip.items())
{
	Write-Host "..unpack" $item.Name
	$shell.Namespace($scriptDir).copyhere($item, 0x14);
}
Write-Host "Removing Zip"
Remove-Item $zipFile
Write-Host "Done fetching DolphinVM.zip" $VMversion

Upgrade to Dolphin VM v7.0.31

# Powershell script to pull the VM files from GitHub into the current folder.
# Edit the following to match the version of the VM that is compatible with this image

param
(
    [string]$VMversion="v7.0.31"
)

Try
{
	$scriptDir = Split-Path $script:MyInvocation.MyCommand.Path;
	Write-Host "Fetching DolphinVM.zip" $VMversion
	$source = "https://github.com/dolphinsmalltalk/DolphinVM/releases/download/$VMversion/DolphinVM.zip";
	$zipFile = $scriptDir+"\DolphinVM.zip";
	Invoke-WebRequest $source -OutFile $zipFile;
}
Catch
{
	Write-Host "Unable to fetch DolphinVM.zip" $VMversion;
	Break;
}

$shell = new-object -com shell.application;
$zip = $shell.NameSpace($zipFile);
foreach($item in $zip.items())
{
	Write-Host "..unpack" $item.Name
	$shell.Namespace($scriptDir).copyhere($item, 0x14);
}
Write-Host "Removing Zip"
Remove-Item $zipFile
Write-Host "Done fetching DolphinVM.zip" $VMversion


param([String]$Version="0.0.0");

ForEach ($category in "Core", "Modules", "Bundles")
{
    ForEach ($folder in (Get-ChildItem -Path $category -Directory))
    {
        dotnet pack $folder.FullName -c Release;
        nuget push "$($folder.FullName)\bin\Release\$($folder.Name).$($Version).nupkg";
        nuget push "$($folder.FullName)\bin\Release\$($folder.Name).$($Version).snupkg";
    }
}

Add nologo to publish script

param([String]$Version="0.0.0");

ForEach ($category in "Core", "Modules", "Bundles")
{
    ForEach ($folder in (Get-ChildItem -Path $category -Directory))
    {
        dotnet pack $folder.FullName --configuration Release --nologo;
        nuget push "$($folder.FullName)\bin\Release\$($folder.Name).$($Version).nupkg";
        nuget push "$($folder.FullName)\bin\Release\$($folder.Name).$($Version).snupkg";
    }
}


function New-Guid {
    [System.Guid]::NewGuid().ToString("d").Substring(0, 6).Replace("-", "")
}

Change test framework to use 4 chars of guid for random names.

function New-Guid {
    [System.Guid]::NewGuid().ToString("d").Substring(0, 4).Replace("-", "")
}


#
# Filename: RemoveSolution.ps1
#
param(
[string]$SolutionName, #The unique CRM solution name
[string]$CrmConnectionString, #The connection string as per CRM Sdk
[int]$Timeout=360
)

$ErrorActionPreference = "Stop"

Write-Verbose 'Entering RemoveSolution.ps1'

Write-Verbose "SolutionName = $SolutionName"
Write-Verbose "ConnectionString = $CrmConnectionString"
Write-Verbose "Timeout = $Timeout"

#Script Location
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
Write-Verbose "Script Path: $scriptPath"

#Load XrmCIFramework
$xrmCIToolkit = $scriptPath + "\Xrm.Framework.CI.PowerShell.Cmdlets.dll"
Write-Verbose "Importing CIToolkit: $xrmCIToolkit"
Import-Module $xrmCIToolkit
Write-Verbose "Imported CIToolkit"

$solution = Get-XrmSolution -UniqueSolutionName $SolutionName -ConnectionString $CrmConnectionString -Timeout $Timeout -Verbose

if ($solution -eq $null)
{
    Write-Error "Solution is not currently installed."
}

Write-Host "Removing solution, version: $solution.Version"
Remove-XrmRecord -EntityName "solution" -Id $solution.Id -ConnectionString $CrmConnectionString -Timeout $Timeout -Verbose
Write-Host "Solution removed"

Write-Verbose 'Leaving RemoveSolution.ps1'

Fix to stop script from failing if solution doesn't exist

#
# Filename: RemoveSolution.ps1
#
param(
[string]$SolutionName, #The unique CRM solution name
[string]$CrmConnectionString, #The connection string as per CRM Sdk
[int]$Timeout=360
)

$ErrorActionPreference = "Stop"

Write-Verbose 'Entering RemoveSolution.ps1'

Write-Verbose "SolutionName = $SolutionName"
Write-Verbose "ConnectionString = $CrmConnectionString"
Write-Verbose "Timeout = $Timeout"

#Script Location
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
Write-Verbose "Script Path: $scriptPath"

#Load XrmCIFramework
$xrmCIToolkit = $scriptPath + "\Xrm.Framework.CI.PowerShell.Cmdlets.dll"
Write-Verbose "Importing CIToolkit: $xrmCIToolkit"
Import-Module $xrmCIToolkit
Write-Verbose "Imported CIToolkit"

$solution = Get-XrmSolution -UniqueSolutionName $SolutionName -ConnectionString $CrmConnectionString -Timeout $Timeout -Verbose

if ($solution -eq $null)
{
    Write-Warning "Solution is not currently installed."
}
else
{
	Write-Host "Removing solution, version: $solution.Version"
	Remove-XrmRecord -EntityName "solution" -Id $solution.Id -ConnectionString $CrmConnectionString -Timeout $Timeout -Verbose
	Write-Host "Solution removed"
}

Write-Verbose 'Leaving RemoveSolution.ps1'


$ffmpeg = "ffmpeg-20191118.0.0-d831edc"
$version = ($ffmpeg -split '-')[1]
$rel32 = "$ffmpeg-lgpl21-v142-static-md-x86"
$rel64 = "$ffmpeg-lgpl21-v142-static-md-x64"
$wc = New-Object System.Net.WebClient

if (!(Test-Path "$rel32.7z")) { $wc.DownloadFile("https://github.com/mcmtroffaes/ffmpeg-msvc-build/releases/download/$version/$rel32.zip", "$env:temp/$rel32.7z") }
if (!(Test-Path "$rel64.7z")) { $wc.DownloadFile("https://github.com/mcmtroffaes/ffmpeg-msvc-build/releases/download/$version/$rel64.zip", "$env:temp/$rel64.7z") }

if (!(Test-Path $rel32)) { 7z x "$env:temp/$rel32.7z" }
if (!(Test-Path $rel64)) { 7z x "$env:temp/$rel64.7z" }

Remove unneeded files after download.

$ffmpeg = "ffmpeg-20191118.0.0-d831edc"
$version = ($ffmpeg -split '-')[1]
$rel32 = "$ffmpeg-lgpl21-v142-static-md-x86"
$rel64 = "$ffmpeg-lgpl21-v142-static-md-x64"
$wc = New-Object System.Net.WebClient

if (!(Test-Path "$rel32.7z")) { $wc.DownloadFile("https://github.com/mcmtroffaes/ffmpeg-msvc-build/releases/download/$version/$rel32.zip", "$env:temp/$rel32.7z") }
if (!(Test-Path "$rel64.7z")) { $wc.DownloadFile("https://github.com/mcmtroffaes/ffmpeg-msvc-build/releases/download/$version/$rel64.zip", "$env:temp/$rel64.7z") }

if (!(Test-Path $rel32)) { 7z x "$env:temp/$rel32.7z" }
if (!(Test-Path $rel64)) { 7z x "$env:temp/$rel64.7z" }

Get-ChildItem * -Recurse -Include vcpkg_abi_info.txt, *.cmake, vpx*.lib, vpx*.pdb, zlib*.lib, pkgconfig, libvpx, zlib, vpx, zconf.h, zlib.h | Remove-Item -Recurse -Verbose


Add PowerShell script to start Docker stack

#!ps1

if (Get-Command docker -errorAction SilentlyContinue)
{
    Write-Host "Deploying stack"
    docker stack deploy func --compose-file ./docker-compose.yml
}
else
{
    Write-Host "Unable to find docker command, please install Docker (https://www.docker.com/) and retry"
}


$deployToolsDir = Split-Path ((Get-Variable MyInvocation -Scope 0).Value.MyCommand.Path)

if (Test-Path variable:\OctopusParameters)
{
    foreach($kp in $OctopusParameters.GetEnumerator())
    {
        Set-Content ("env:\" + $kp.Key) ($kp.Value) -Force
    }
}

if(!(Test-Path "env:\ConfigOnly"))
{
    Set-Content "env:\ConfigOnly" $false
}

function ensconce
{
    $results = & "$deployToolsDir\ensconce.exe" $args 2>&1
    if ($LASTEXITCODE -ne 0)
    {
        throw (
"Ensconce operation failed.
$results")
    }
    $results
}

Fix ensconce function when used with pipe operator.

$deployToolsDir = Split-Path ((Get-Variable MyInvocation -Scope 0).Value.MyCommand.Path)

if (Test-Path variable:\OctopusParameters)
{
    foreach($kp in $OctopusParameters.GetEnumerator())
    {
        Set-Content ("env:\" + $kp.Key) ($kp.Value) -Force
    }
}

if(!(Test-Path "env:\ConfigOnly"))
{
    Set-Content "env:\ConfigOnly" $false
}

function ensconce
{
    if (@($input).Count -ne 0)
    {
        $input.Reset()
        $results = $input | & "$deployToolsDir\ensconce.exe" $args 2>&1
    }
    else {
        $results = & "$deployToolsDir\ensconce.exe" $args 2>&1
    }
    if ($LASTEXITCODE -ne 0)
    {
        throw (
"Ensconce operation failed.
$results")
    }
    $results
}


if (!(Test-Path C:\vagrant\registry-v2)) {
  mkdir -p C:\vagrant\registry-v2
}
docker run --restart=always -d -p 5000:5000 -v "C:\vagrant\registry-v2:C:\data" sixeyed/registry:nanoserver

Update registry image, use C:/registry volume

if (!(Test-Path C:\vagrant\registry-v2)) {
  mkdir -p C:\vagrant\registry-v2
}
docker run --restart=always -d -p 5000:5000 -v "C:\vagrant\registry-v2:C:\registry" stefanscherer/registry-windows:2.6.0


#Requires -Modules VagrantMessages

param(
    [Parameter(Mandatory=$true)]
    [string]$VmId
)

try {
    $VM = Hyper-V\Get-VM -Id $VmId
    Hyper-V\Get-VMHardDiskDrive -VMName $VM
} catch {
    Write-ErrorMessage "Failed to retrieve all disk info from ${VM}: ${PSItem}"
    exit 1
}

Format output from json to return to hyper-v driver

#Requires -Modules VagrantMessages

param(
    [Parameter(Mandatory=$true)]
    [string]$VmId
)

try {
    $VM = Hyper-V\Get-VM -Id $VmId
    $Disks = @(Hyper-V\Get-VMHardDiskDrive -VMName $VM)
} catch {
    Write-ErrorMessage "Failed to retrieve all disk info from ${VM}: ${PSItem}"
    exit 1
}

$result = ConvertTo-json $Disks
Write-OutputMessage $result


param(
  [string]$name
)

if (! $name) {
  $name = "dev"
}

# ensure that we are running as administrator
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {#
  Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" -Name $name" -Verb RunAs; exit
}

# create a virtual switch
if (((Get-VMSwitch).name | grep docker) -ne "docker") {
  $description=(Get-NetAdapter).InterfaceDescription | grep -v Hyper-V
  New-VMSwitch -NetAdapterInterfaceDescription $description -Name "docker"

  Write-Host "Waiting for internet connectivity"
  Sleep 15
}

# create a Hyper-V Linux docker machine
docker-machine create -d hyperv --hyperv-virtual-switch "docker" $name

# known issues
# https://github.com/docker/machine/issues/2267
# https://github.com/docker/machine/issues/2362
# workaround: https://github.com/docker/machine/issues/2267#issuecomment-156426874
docker-machine start $name
docker-machine regenerate-certs -f $name

# windows docker client has different API version
# workaround: update the docker engine in the Hyper-V Linux docker machine
docker-machine ssh $name sudo /etc/init.d/docker stop
docker-machine ssh $name sudo curl -o /usr/local/bin/docker https://master.dockerproject.org/linux/amd64/docker
docker-machine ssh $name sudo /etc/init.d/docker start

Remove updating linux docker engine


$req_query_iata

$Fields = @{"iatacode" = "$req_query_iata"}
$WebResponse = Invoke-RestMethod -Uri "http://www.airlinecodes.co.uk/airlcoderes.asp" -Method Post -Body $Fields -Verbose

$regex = '<TD>\D{3}<\/TD>'

$WebResponse -match $regex

$result = $Matches[0]

Out-File -Encoding Ascii $res -inputObject $result.Substring(4,3)

Use different database for IATA code.

$req_query_iata

# status Y means current data
$Fields = @{"status" = "Y"; "iataairl" = "$req_query_iata"}
$WebResponse = Invoke-RestMethod -Uri "http://avcodes.co.uk/airlcoderes.asp" -Method Post -Body $Fields -Verbose

$regex = 'ICAO Code:<br /> \D{3}'

$WebResponse -match $regex
$result = $Matches[0]

Out-File -Encoding Ascii $res -inputObject $result.Split(';')[1]


#!/usr/local/bin/pwsh
#Terminate on powershell error in function or cmd-let. External
#commands still need to be checked with $LastExitCode, $? checks
#both, $Error contains a full set of last errors and can be cleared.
#This preference can be reset on command basis.
$ErrorActionPreference="Stop"
$Env:PSModulePath="${Env:PSModulePath}:$PSScriptRoot/lib"
Import-Module ConfigReader

$cfgFile = "${PSScriptRoot}/etc/holiday.conf"
if (Test-Path $cfgFile) {
    $cfg = ConfigReader\Read-ConfigFile $cfgFile
} else {
    $cfg = @{ "global" = @( @{ "port"=@(1970); "server"=@("localhost") } ) }
}
#$cfg.global[0].port[0]
#$cfg.global[0].privileged[0]
#$cfg.global[0].privileged[1]

Add stub to load user files.

#!/usr/local/bin/pwsh
#Terminate on powershell error in function or cmd-let. External
#commands still need to be checked with $LastExitCode, $? checks
#both, $Error contains a full set of last errors and can be cleared.
#This preference can be reset on command basis.
$ErrorActionPreference="Stop"
$Env:PSModulePath="${Env:PSModulePath}:$PSScriptRoot/lib"
Import-Module ConfigReader

function Load-UsrFile ([String]$fn) {
    $userName = Split-Path -LeafBase $fn
    $lines = Get-Content -Path $fn
    #if ($lines.Count -lt 1)
    $usr = @{ group = $lines[0]; table = @() }
    for ($i = 1; $i -le $lines.Count; $i++) {
        Write-Host("Holiday line:" + $lines[$i])
        #FIXME: Split and check
        if ($lines[$i] -gt 0) {
            $usr.table += $lines[$i]
        }
    }
    $userDicts.Add($userName, $usr)
}

$cfgFile = "${PSScriptRoot}/etc/holiday.conf"
$userDicts = @{}
if (Test-Path $cfgFile) {
    $cfg = ConfigReader\Read-ConfigFile $cfgFile
} else {
    $cfg = @{ "global" = @( @{ "port"=@(1970); "server"=@("localhost") } ) }
}
Get-ChildItem  -Filter *.usr | ForEach-Object { Load-UsrFile $_.FullName }
#Then startup server

#$cfg.global[0].port[0]
#$cfg.global[0].privileged[0]
#$cfg.global[0].privileged[1]


$msbuild = "C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe"

cd ..
Invoke-Expression ($msbuild + " BuildSample.sln /p:Configuration=Release /t:Clean")
Invoke-Expression ($msbuild + " BuildSample.sln /p:Configuration=Release /t:Rebuild")

explorer Downloads


git commit --amend
-avoid if you've already pushed
-change the commit message, or
-change the snapshot with `add` or `rm`
-warning: is a mini-rebase, changes the SHA

git rebase -i
-supply the parent of the last commit you want to edit


## Download Chocolatey Package Manager
if(-not $env:ChocolateyInstall -or -not (Test-Path "$env:ChocolateyInstall"))
{
	iex ((new-object net.webclient).DownloadString('http://chocolatey.org/install.ps1'))
}

## Development Tools - Common

cinst papercut

## cinst redis

## cinst jenkins

## cinst rabbitmq

## cinst MongoVUE

## Development Tools - Android

## cinst android-sdk

## cinst python3

## cinst ruby

## cinst python

Add java and python dev tools section

## Download Chocolatey Package Manager
if(-not $env:ChocolateyInstall -or -not (Test-Path "$env:ChocolateyInstall"))
{
	iex ((new-object net.webclient).DownloadString('http://chocolatey.org/install.ps1'))
}

## Development Tools - Common

cinst papercut

## cinst redis

## cinst jenkins

## cinst rabbitmq

## cinst mongodb

## cinst MongoVUE

## Development Tools - Java

cinst java.jdk

## cinst Grails

## Development Tools - Ruby

## cinst ruby

## Development Tools - Android

## cinst android-sdk

## Development Tools - Python

## cinst python3

## cinst python

## cinst easy.install


## This configuration file uses BoxStarter to configure the system
## and Chocolatey to install necessary packages

## Development Tools - Node.JS & Yarn

choco install nvm

choco install yarn

nvm install latest

# choco install visualstudio2019-workload-node

Tweak node based on Microsoft's version

## This configuration file uses BoxStarter to configure the system
## and Chocolatey to install necessary packages

# Based on https://github.com/microsoft/azure-pipelines-image-generation/blob/master/images/win/scripts/Installers/Install-NodeLts.ps1

$PrefixPath = 'C:\npm\prefix'
$CachePath = 'C:\npm\cache'

New-Item -Path $PrefixPath -Force -ItemType Directory
New-Item -Path $CachePath -Force -ItemType Directory

choco install nodejs-lts -y --force

setx NPM_CONFIG_PREFIX $PrefixPath /M
$env:NPM_CONFIG_PREFIX = $PrefixPath

setx NPM_CONFIG_CACHE $CachePath /M
$env:NPM_CONFIG_CACHE = $CachePath

npm config set registry http://registry.npmjs.org/

npm install -g cordova
npm install -g grunt-cli
npm install -g gulp-cli
npm install -g parcel-bundler
npm install -g --save-dev webpack webpack-cli
npm install -g yarn

## Development Tools - Node.JS & Yarn

choco install nvm

nvm install latest

# choco install visualstudio2019-workload-node


$env:TGSVersion = [System.Diagnostics.FileVersionInfo]::GetVersionInfo("$env:APPVEYOR_BUILD_FOLDER/artifacts/ServerHost/Tgstation.Server.Host.dll").FileVersion

Write-Host "TGS Version: $env:TGSVersion"

if (($env:CONFIGURATION -match "Release") -And ($env:APPVEYOR_REPO_BRANCH -match "master") -And ($env:APPVEYOR_REPO_COMMIT_MESSAGE -match "\[TGSDeploy\]")) {
    Write-Host "Deploying..."
    $env:TGSDeploy = "Do it."

    Write-Host "Generating release notes..."
    dotnet run -p "$env:APPVEYOR_BUILD_FOLDER/tools/ReleaseNotes" $env:TGSVersion
    $env:TGSDraftNotes = !($?)
    $releaseNotesPath = "$env:APPVEYOR_BUILD_FOLDER/tools/ReleaseNotes/release_notes.md"
    Write-Host "Reading release notes from $releaseNotesPath..."
    if (Test-Path $releaseNotesPath -PathType Leaf) {
        $env:TGSReleaseNotes = [IO.File]::ReadAllText($releaseNotesPath)
    }
    else {
        Write-Host "Release note generation failed, release will be created as a draft!"
        $env:TGSReleaseNotes = "Automatic generation failed, please fill manually!"
    }

    if ($env:APPVEYOR_REPO_COMMIT_MESSAGE -match "\[NugetDeploy\]") {
        $env:NugetDeploy = "Do it."
        Write-Host "Nuget deployment enabled"
    }
}

Fix release notes path in build

$env:TGSVersion = [System.Diagnostics.FileVersionInfo]::GetVersionInfo("$env:APPVEYOR_BUILD_FOLDER/artifacts/ServerHost/Tgstation.Server.Host.dll").FileVersion

Write-Host "TGS Version: $env:TGSVersion"

if (($env:CONFIGURATION -match "Release") -And ($env:APPVEYOR_REPO_BRANCH -match "master") -And ($env:APPVEYOR_REPO_COMMIT_MESSAGE -match "\[TGSDeploy\]")) {
    Write-Host "Deploying..."
    $env:TGSDeploy = "Do it."

    Write-Host "Generating release notes..."
    $bf = $env:APPVEYOR_BUILD_FOLDER
    dotnet run -p "$bf/tools/ReleaseNotes" $env:TGSVersion
    $env:TGSDraftNotes = !($?)
    $releaseNotesPath = "$bf/release_notes.md"
    Write-Host "Reading release notes from $releaseNotesPath..."
    if (Test-Path $releaseNotesPath -PathType Leaf) {
        $env:TGSReleaseNotes = [IO.File]::ReadAllText($releaseNotesPath)
    }
    else {
        Write-Host "Release note generation failed, release will be created as a draft!"
        $env:TGSReleaseNotes = "Automatic generation failed, please fill manually!"
    }

    if ($env:APPVEYOR_REPO_COMMIT_MESSAGE -match "\[NugetDeploy\]") {
        $env:NugetDeploy = "Do it."
        Write-Host "Nuget deployment enabled"
    }
}


trap [Management.Automation.CommandNotFoundException] {
  Write-Error 'Docker cannot be found. Make sure it is installed and added to the path.'
  Start-Process -FilePath 'https://docs.docker.com/docker-for-windows/install/'
  continue;
}

docker run --rm -it -v ${PSScriptRoot}:/nunit-console -w=/nunit-console mono:5.10.0 bash build.sh $args

Switch to using my docker image

trap [Management.Automation.CommandNotFoundException] {
  Write-Error 'Docker cannot be found. Make sure it is installed and added to the path.'
  Start-Process -FilePath 'https://docs.docker.com/docker-for-windows/install/'
  continue;
}

docker run --rm -it -v ${PSScriptRoot}:/nunit-console -w=/nunit-console rprouse/nunit-docker:latest bash build.sh $args


Describe "Get-Host" {
    It "Should return a type of InternalHost for Get-Host cmdlet" {

	(Get-Host).GetType().Name | Should Be InternalHost

    }

    It "Should have $ host variable be equivalent to Get-Host object" {

	Get-Host | Should Be $host

    }
}

Add Unit Test for Get-Host

Describe "Get-Host DRT Unit Tests" -Tags DRT{
    It "Should works proper with get-host" {
        $results = Get-Host
        $results | Should Be $Host
        $results.GetType().Name | Should Be InternalHost
    }
}

Describe "Get-Host" {
    It "Should return a type of InternalHost for Get-Host cmdlet" {

	(Get-Host).GetType().Name | Should Be InternalHost

    }

    It "Should have $ host variable be equivalent to Get-Host object" {

	Get-Host | Should Be $host

    }
}


Add a script to decode kubernetes secret.

# Copyright (c) 2019 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.

##############################################################################
#.SYNOPSIS
# Decode a Kubernetes secret to a file.
#
#.DESCRIPTION
# Invokes kubectl.
#
#.PARAMETER SecretName
# The Kubernetes secret name.
#
#.PARAMETER FileName
# The name of the file in the Kubernetes secret.
#
#.PARAMETER OutputFileName
# Optional.  The name of the file to write.  Clobbers any existing file.
# If none, then dumps the file contents to stdout.
#
#.EXAMPLE
# .\Get-SecretFile.ps1 my-kubernetes-secret super-secrets.json super-secrets.json
##############################################################################

param(
    [Parameter(Mandatory=$true)][string]$SecretName,
    [Parameter(Mandatory=$true)][string]$FileName,
    [string]$OutputFileName)

$base64text = (kubectl get secret $SecretName -o json | ConvertFrom-Json).data.$FileName
$bytes = [System.Convert]::FromBase64String($base64text)
if ($OutputFileName) {
    [io.file]::WriteAllBytes($OutputFileName, $bytes)
} else {
    [System.Text.Encoding]::UTF8.GetString($bytes)
}


<#
  .DESCRIPTION
  Create a docker compose .env file
#>
$scriptPath = Split-Path -parent $PSCommandPath
$envFilePath = Resolve-Path "$scriptPath\..\.env"
$getEnvCommand = Resolve-Path "$scriptPath\..\lib\killrvideo-docker-common\get-environment.ps1"

# Base environment variables to be written
$dockerEnv = @("COMPOSE_PROJECT_NAME=killrvideoweb", "COMPOSE_FILE=.\lib\killrvideo-docker-common\docker-compose.yaml")

# Get the docker environment using the common script and add to array
& "$getEnvCommand" |% { $dockerEnv += $_ }

# We have to use .NET to do this so it gets written as UTF-8 without the BOM
$Utf8NoBom = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::WriteAllLines($envFilePath, $dockerEnv, $Utf8NoBom)
Write-Host "Environment file written to $envFilePath"

Handle environment not being present initially in script

<#
  .DESCRIPTION
  Create a docker compose .env file
#>
$scriptPath = Split-Path -parent $PSCommandPath
$envFilePath = "$scriptPath\..\.env"
$getEnvCommand = Resolve-Path "$scriptPath\..\lib\killrvideo-docker-common\get-environment.ps1"

# Base environment variables to be written
$dockerEnv = @("COMPOSE_PROJECT_NAME=killrvideoweb", "COMPOSE_FILE=.\lib\killrvideo-docker-common\docker-compose.yaml")

# Get the docker environment using the common script and add to array
& "$getEnvCommand" |% { $dockerEnv += $_ }

# We have to use .NET to do this so it gets written as UTF-8 without the BOM
$Utf8NoBom = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::WriteAllLines($envFilePath, $dockerEnv, $Utf8NoBom)
$envFilePath = Resolve-Path $envFilePath
Write-Host "Environment file written to $envFilePath"


Add script to download test files from GH folder via build

[CmdletBinding()]
param (
    [Parameter(Mandatory=$false)][string]$githubTestFilesFolderUri,
    [Parameter(Mandatory=$false)][string]$githubBuildFilesFolderUri
)

if(!$githubTestFilesFolderUri) {
    # default to azure quickstart template uri
    Write-Host "Defaulting to azure quick start uri"
    $githubTestFilesFolderUri = "https://api.github.com/repos/Azure/azure-quickstart-templates/contents/test/solution-template-validation-tests/test"
}

if(!$githubBuildFilesFolderUri) {
    # default to azure quickstart template uri
    Write-Host "Defaulting to azure quick start uri"
    $githubBuildFilesFolderUri = "https://api.github.com/repos/Azure/azure-quickstart-templates/contents/test/solution-template-validation-tests/buildfiles"
}

Write-Host "Getting contents from $githubTestFilesFolderUri"
$folderContents = Invoke-WebRequest $githubTestFilesFolderUri | Select-Object -ExpandProperty Content | ConvertFrom-Json

Write-Host "Creating test directory if one doesn't exist already"
$path = (Get-Item -Path ".\" -Verbose).FullName + "\test"
If(!(test-path $path))
{
    Write-Host "Creating test directory"
    New-Item -ItemType Directory -Force -Path $path
}

cd $path
foreach($file in $folderContents)
{
    Write-Host "Downloading file $file.name"
    Invoke-WebRequest $file.download_url -OutFile $file.name
}

Write-Host "Listing files downloaded"
dir

# go back to current directory
cd ..

Write-Host "Getting contents from $githubBuildFilesFolderUri"
$folderContents = Invoke-WebRequest $githubBuildFilesFolderUri | Select-Object -ExpandProperty Content | ConvertFrom-Json

foreach($file in $folderContents)
{
    Write-Host "Downloading file $file.name"
    Invoke-WebRequest $file.download_url -OutFile $file.name
}

$packageJsonFile = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/test/solution-template-validation-tests/package.json"
Write-Host "Downloading package.json file from $packageJsonFile"
Invoke-WebRequest $packageJsonFile -OutFile "package.json"

Write-Host "Listing files downloaded"
dir


Add helper script for pulling in latest from subtree dependencies

<#
  .DESCRIPTION
  Pull the latest from the projects that are git subtrees.
#>

git subtree pull --prefix lib/killrvideo-docker-common git@github.com:KillrVideo/killrvideo-docker-common.git master --squash
git subtree pull --prefix lib/killrvideo-service-protos git@github.com:KillrVideo/killrvideo-service-protos.git master --squash


function ZipFile
{
	param(
		[String]$sourceFile,
		[String]$zipFile
	)

	set-alias sz "C:\Program Files\7-Zip\7z.exe"
	sz a -tzip -r $zipFile $sourceFile | Out-Null
}

$root = $PSScriptRoot
$source = $root.Replace("deployment", "") + "\source"
$version = Read-Host -Prompt "What version are we building?"

# build for mongo db
Write-Host "Building SqlServerReportRunner version $version"
$binfolder = "$source\SqlServerReportRunner\bin\Release"
[system.io.file]::Delete("$binfolder\Connections.config")
$zip = "$root\Output\SqlServerReportRunner_v$version.zip"
[system.io.file]::Delete($zip)
ZipFile -sourcefile "$binfolder\*.*" -zipfile $zip

Write-Host "Done" -BackgroundColor Green -ForegroundColor White

Update to deployment script for 7-zip

function ZipFile
{
	param(
		[String]$sourceFile,
		[String]$zipFile
	)

	set-alias sz "C:\Program Files (x86)\7-Zip\7z.exe"
	sz a -tzip -r $zipFile $sourceFile | Out-Null
}

$root = $PSScriptRoot
$source = $root.Replace("deployment", "") + "\source"
$version = Read-Host -Prompt "What version are we building?"

# build for mongo db
Write-Host "Building SqlServerReportRunner version $version"
$binfolder = "$source\SqlServerReportRunner\bin\Release"
[system.io.file]::Delete("$binfolder\Connections.config")
$zip = "$root\Output\SqlServerReportRunner_v$version.zip"
[system.io.file]::Delete($zip)
ZipFile -sourcefile "$binfolder\*.*" -zipfile $zip

Write-Host "Done" -BackgroundColor Green -ForegroundColor White


npm i -g tfx-cli
tfx extension create --manifest-globs vss-extension.json

Fix security vulnerability in npm lodash used in PackageVSTS cake.build task

npm i npm@latest -g
npm i -g tfx-cli
tfx extension create --manifest-globs vss-extension.json


Add PowerShell script to upload VSIX to MyGet feed

$artifactsSearchPattern = "./*.vsix"
$artifactsCollection = (Get-ChildItem $artifactsSearchPattern -Recurse)

$vsixMyGetUploadEndpoint = "https://www.myget.org/F/nanoframework-dev/vsix/upload"

# for the environment variable MyGetToken to work here it has to be set in AppVeyor UI

foreach($file in $artifactsCollection)
{
    'Uploading VSIX package to MyGet feed...' | Write-Host -ForegroundColor White -NoNewline

    $webClient = New-Object System.Net.WebClient
    $webClient.Headers.add('X-NuGet-ApiKey', $env:MyGetToken)
    $webClient.UploadFile($vsixMyGetUploadEndpoint, 'POST', $file)
    'OK' | Write-Host -ForegroundColor Green
}


chcp 65001 | out-null

function prompt {
    '[' + $env:username + '@' + $env:computername + ' ' + $pwd + "]`r`n$ "
}

function .. {
    Set-Location ..
}
function ... {
    Set-Location ..\..
}
function .... {
    Set-Location ..\..\..
}

Set-Alias l Get-ChildItem
Set-Alias ll Get-ChildItem
Set-Alias open Invoke-Item

if (Test-Path 'C:\Program Files\Sublime Text 3') {
    Set-Alias edit 'C:\Program Files\Sublime Text 3\sublime_text'
}

if (Test-Path 'C:\Program Files (x86)\Microsoft VS Code') {
    Set-Alias edit 'C:\Program Files (x86)\Microsoft VS Code\code'
}

[net.webrequest]::defaultwebproxy.credentials = [net.credentialcache]::defaultcredentials

Test properly for atom and code availability

chcp 65001 | out-null

function prompt {
    '[' + $env:username + '@' + $env:computername + ' ' + $pwd + "]`r`n$ "
}

function .. {
    Set-Location ..
}
function ... {
    Set-Location ..\..
}
function .... {
    Set-Location ..\..\..
}

Set-Alias l Get-ChildItem
Set-Alias ll Get-ChildItem
Set-Alias open Invoke-Item

if (Test-Path 'C:\Program Files\Sublime Text 3') {
    Set-Alias edit 'C:\Program Files\Sublime Text 3\sublime_text'
}
if (Get-Command "atom" -ErrorAction SilentlyContinue) {
    Set-Alias edit atom
}
if (Get-Command "code" -ErrorAction SilentlyContinue) {
    Set-Alias edit code
}

[net.webrequest]::defaultwebproxy.credentials = [net.credentialcache]::defaultcredentials


# Framework to use when generating coverage. Must be a "real" framework, i.e. not netstandard.
$framework = "netcoreapp3.1";
# The file path passed to coverlet...
$coverletWantedOutput = "$PSScriptRoot\coverage.xml";
# ...which will result in the following filename.
$coverletActualOutput = "$PSScriptRoot\" + "coverage.{framework}.xml".Replace("{framework}", $framework);
If (Test-Path $coverletActualOutput) {
	Remove-Item $coverletActualOutput -Force
}

dotnet test -f $framework /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:CoverletOutput=$coverletWantedOutput /p:Exclude="[xunit.*]*" ../source/tusdotnet.sln

$key = Read-Host -Prompt 'Input Codecov key'

if(-not (Test-Path $coverletActualOutput)) {
	throw "$coverletActualOutput was not found";
}
./codecov.sh -t $key

Use net6.0 as framework for code coverage

# Framework to use when generating coverage. Must be a "real" framework, i.e. not netstandard.
$framework = "net6.0";
# The file path passed to coverlet...
$coverletWantedOutput = "$PSScriptRoot\coverage.xml";
# ...which will result in the following filename.
$coverletActualOutput = "$PSScriptRoot\" + "coverage.{framework}.xml".Replace("{framework}", $framework);
If (Test-Path $coverletActualOutput) {
	Remove-Item $coverletActualOutput -Force
}

dotnet test -f $framework /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:CoverletOutput=$coverletWantedOutput /p:Exclude="[xunit.*]*" ../source/tusdotnet.sln

$key = Read-Host -Prompt 'Input Codecov key'

if(-not (Test-Path $coverletActualOutput)) {
	throw "$coverletActualOutput was not found";
}
./codecov.sh -t $key


Add PS script for electron-winstaller packaging

<#
Package script for electron-winstaller

The NPM package electron-winstaller allows developers to
build Windows installers for Electron apps using Squirrel
(https://github.com/electron/windows-installer)

This script copies the required files into a single folder
which can then be copied to the electron-winstaller/vendor folder
(either manually or in an automated way).
#>

# Stop the script if an error occurs
$ErrorActionPreference = "Stop"
$In = ".\build\Release\"
$Out = ".\build\electron-winstaller\"
$Folders = @("./build", "./packages", "./test/bin", "./test/obj")

# Ensure a clean state by removing build/package folders
foreach ($Folder in $Folders) {
    if (Test-Path $Folder) {
        Remove-Item -path $Folder -Recurse -Force
    }
}

# Build Squirrel
git submodule update --init --recursive
.\.NuGet\NuGet.exe restore
msbuild /p:Configuration=Release

# Create the electron-winstaller folder
New-Item -Path $Out -ItemType "directory" | Out-Null

# Copy over all files we need
Copy-Item "$In\net45\Update.exe" -Destination "$Out\Squirrel.exe"
Copy-Item "$In\net45\update.com" -Destination "$Out\Squirrel.com"
Copy-Item "$In\net45\Update.pdb" -Destination "$Out\Squirrel.pdb"
Copy-Item "$In\Win32\Setup.exe" -Destination $Out
Copy-Item "$In\Win32\Setup.pdb" -Destination $Out
Copy-Item "$In\net45\Update-Mono.exe" -Destination "$Out\Squirrel-Mono.exe"
Copy-Item "$In\net45\Update-Mono.pdb" -Destination "$Out\Squirrel-Mono.pdb"
Copy-Item "$In\Win32\StubExecutable.exe" -Destination $Out
Copy-Item "$In\net45\SyncReleases.exe" -Destination $Out
Copy-Item "$In\net45\SyncReleases.pdb" -Destination $Out
Copy-Item "$In\Win32\WriteZipToSetup.exe" -Destination $Out
Copy-Item "$In\Win32\WriteZipToSetup.pdb" -Destination $Out

Write-Output "Successfully copied files for electron-winstaller to build/electron-winstaller."


$hostname = $(get-childitem -path env:computername).value
$ipaddress = $(ipconfig | where {$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; $Matches[1])

$puppet = 'C:\Program Files\Puppet Labs\Puppet\bin\puppet.bat'
Test-Path $puppet
if($?){
    Write-Host "puppet-agent OK"
    choco upgrade puppet-agent
} else {
    choco install puppet-agent --force -y
}
& $puppet module install puppetlabs-chocolatey --version 2.0.2

Clean up a little code

$hostname = $(get-childitem -path env:computername).value
$ipaddress = $(ipconfig | where {$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; $Matches[1])

$puppet = 'C:\Program Files\Puppet Labs\Puppet\bin\puppet.bat'
Test-Path $puppet
if($?){
    Write-Host "puppet-agent OK"
    choco upgrade puppet-agent
} else {
    choco install puppet-agent --force -y
}
& $puppet module install puppetlabs-chocolatey --version 2.0.2
& $puppet 'apply' '--test' "$PSScriptRoot\test.pp"

nssm set consul Application (Get-Command consul).Path
nssm set consul AppParameters agent -bootstrap -server -ui -node $hostname -advertise $ipaddress --data-dir c:\var\consul


param([String]$oldVersion="", [String]$newVersion="")
iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/StephenCleary/BuildTools/18aed44c432381eaa11329d82f63dfaf835d219c/Version.ps1'))

Fix bug in version script.