Invoke-BuildStep.task.ps1

param (
    [Parameter(Mandatory = $false)]
    $OutputPath,

    [Parameter(Mandatory = $false)]
    $ProjectPath,

    [Parameter(Mandatory = $false)]
    $MetadataObjectAsJson = @{}
)


$GitVersionExe = (Join-Path $PSScriptRoot "\Dependencies\GitVersion_3.6.5\GitVersion.exe")
$ConventionalChangelogExe = (Join-Path $PSScriptRoot "\Dependencies\conventional-changelog\conventional-changelog.cmd")

Write-Verbose ("GitVersionExe: [{0}]" -f $GitVersionExe) -Verbose
Write-Verbose ("ConventionalChangelogExe: [{0}]" -f $ConventionalChangelogExe) -Verbose

# NOTE: Defoult tasks chain
Task default UpdateConfiguration, Metadata, Csproj, Changelog

# NOTE: Update configuration
Task UpdateConfiguration {
    Set-Content $ProjectPath\GitVersion.yml @"
branches:
    master:`
      mode: ContinuousDeployment
      tag: stable
      increment: None
      prevent-increment-of-merged-branch-version: true
      track-merge-target: false
    release:
      mode: ContinuousDeployment
      tag: release
      increment: None
      prevent-increment-of-merged-branch-version: true
      track-merge-target: false
    (pull|pull\-requests|pr)[/-]:
      mode: ContinuousDeployment
      tag: pr
      increment: None
      prevent-increment-of-merged-branch-version: false
      tag-number-pattern: '[/-](?<number>\d+)[-/]'
      track-merge-target: false
    hotfix(es)?[/-]:
      mode: ContinuousDeployment
      tag: hotfix
      increment: None
      prevent-increment-of-merged-branch-version: false
      track-merge-target: false
    support[/-]:
      mode: ContinuousDeployment
      tag: support
      increment: None
      prevent-increment-of-merged-branch-version: true
      track-merge-target: false
    develop:
      mode: ContinuousDeployment
      tag: develop
      increment: None
      prevent-increment-of-merged-branch-version: false
      track-merge-target: true
"@


}
# NOTE: Generate metadata
Task Metadata {
    Set-Location $ProjectPath

    $MetadataFile = Resolve-Path $ProjectPath\*.metadata.json
    Write-Verbose ("MetadataPath: {0}" -f $MetadataFile) -Verbose
    if (-not (Test-Path $MetadataFile)) 
    {
        throw [System.IO.FileNotFoundException] "$MetadataFile not found."
    }else{
        Get-Content $MetadataFile
        $MetadataFileObject = Get-Content $MetadataFile | Out-String | ConvertFrom-Json
    }
    # NOTE Load metadata from path if exist

    $CurrentTime = Get-Date -Format "MM-dd-yyyy-hh-mm-ss"
    
    $GitVersionObject = ConvertFrom-Json ( & $GitVersionExe | Out-String)

    $MetadataObject = [PSCustomObject]@{
        Name      = if ($MetadataFileObject.Name) {$MetadataFileObject.Name} else {"none"};  
        Version   = if ($GitVersionObject.FullSemVer) {$GitVersionObject.FullSemVer} else {"none"};
        Build     = [PSCustomObject] @{
            Time              = $CurrentTime
            BuildId           = if ($env:BUILD_BUILDID) {$env:BUILD_BUILDID} else {"none"};
            DefinitionName    = if ($env:BUILD_DEFINITIONNAME) {$env:BUILD_DEFINITIONNAME} else {"none"};
            BuildNumber       = if ($env:BUILD_BUILDNUMBER) {$env:BUILD_BUILDNUMBER} else {"none"};
            DefinitionVersion = if ($env:BUILD_DEFINITIONVERSION) {$env:BUILD_DEFINITIONVERSION} else {"none"};
            QueuedBy          = if ($env:BUILD_QUEUEDBY) {$env:BUILD_QUEUEDBY} else {"none"};
            RepositoryUri     = if ($env:BUILD_REPOSITORY_URI) {$env:BUILD_REPOSITORY_URI} else {"none"};
            TeamProject       = if ($env:SYSTEM_TEAMPROJECT) {$env:SYSTEM_TEAMPROJECT} else {"none"};
            BuildReason       = if ($env:RELEASE_ENVIRONMENTNAME) {$env:RELEASE_ENVIRONMENTNAME} else {"none"};
            AgentName         = if ($env:AGENT_NAME) {$env:AGENT_NAME} else {"none"};
        }
        SemVer    = $GitVersionObject
        Resources =if ($MetadataFileObject.Resources) {$MetadataFileObject.Resources} else {@()};    
    }

    $MetadataObjectAsJson = $MetadataObject | ConvertTo-Json -depth 100 

    # if (-not ([string]::IsNullOrEmpty($MetadataFileName))){
    # $MetadataFileName = ".metadata.json"
    # }
    # $MetadataOutputFile = (Join-Path $OutputPath $MetadataFileName)
    Write-Verbose ("MetadataAsJson: {0}" -f $MetadataObjectAsJson) -Verbose

    $MetadataObjectAsJson | Out-File $MetadataFile -Force
    Write-Verbose ("Metadata saved to: [{0}]" -f $MetadataFile) -Verbose

    Write-Host "##vso[build.updatebuildnumber]$($GitVersionObject.FullSemVer)"
}
# NOTE: Generate changelog file
Task Changelog {
    Set-Location $ProjectPath
    $ChangelogFile = (Join-Path $OutputPath CHANGELOG.md)
    exec {
        & $ConventionalChangelogExe -p angular -i $ChangelogFile -s -r 0
    }
    Write-Build Green "ChangelogFile: $ChangelogFile"
    Write-Host "##vso[task.setvariable variable=ChangelogFile;]$ChangelogFile"

}
# NOTE: Set version and update all csproj files
Task Csproj {
    # Update Version element in each csproj
    Set-Location $ProjectPath
    Get-ChildItem -Recurse -Filter *.csproj -File |
        ForEach-Object {
        [xml]$CsProjectName = Get-Content $_.FullName
        $Version = $CsProjectName.SelectSingleNode('//Version[last()]')
        if ($Version) {
            $Version.InnerText = $MetadataObject.Version
            $CsProjectName.Save($_.FullName)
        }
    }
}