# Gradle
# Build your Java project and run tests with Gradle using a Gradle wrapper script.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://docs.microsoft.com/azure/devops/pipelines/languages/java

pool:
  vmImage: 'Ubuntu-latest'

variables:
  revision: $[counter('release-number', 0)]
  artifactName: 'Release'
  GRADLE_USER_HOME: $(Pipeline.Workspace)/.gradle

steps:
- task: Cache@2
  inputs:
    key: 'gradle | "$(Agent.OS)" | build.gradle | gradle.properties | src/main/resources/META-INF/accesstransformer.cfg'
    restoreKeys: gradle
    path: $(GRADLE_USER_HOME)
  displayName: Gradle build cache

- powershell: |
    (Get-Content ./gradle.properties).Split([Environment]::NewLine) | % {
        $kvp = $_.Split('=')
        if ($kvp.Count -gt 1) {
            $key = $kvp[0] -replace "\.", "_";
            $value = $kvp[1];
            Write-Host "##vso[task.setvariable variable=javaprops_$key]$value"
        }
    }
  displayName: Create Azure DevOps variables from gradle properties file

- task: Gradle@2
  displayName: Create Release Build
  inputs:
    workingDirectory: ''
    options: '--build-cache --max-workers=1 -PCIRevision=$(javaprops_mod_version).$(revision) -PCIType=RELEASE'
    gradleWrapperFile: 'gradlew'
    gradleOptions: '-Xmx3072m'
    javaHomeOption: 'JDKVersion'
    jdkVersionOption: '1.8'
    jdkArchitectureOption: 'x64'
    publishJUnitResults: false
    testResultsFiles: '**/TEST-*.xml'
    tasks: 'build'

- task: CopyFiles@2
  displayName: Copy Release build to artifact staging
  inputs:
    sourceFolder: './build/libs/'
    contents: 'twilightforest-*-universal.jar'
    targetFolder: $(build.artifactStagingDirectory)
  condition: and(succeeded(), eq(variables['CreateArtifacts'], 'True'))

- task: PublishPipelineArtifact@1
  displayName: 'Publish Artifacts'
  condition: and(succeeded(), eq(variables['CreateArtifacts'], 'True'))
  inputs:
    targetPath: '$(Build.ArtifactStagingDirectory)'
    artifact: '$(artifactName)'
    publishLocation: 'pipeline'

- powershell: |
    $rawpath = "pipelineartifact://teamtwilight/projectId/1ef09d39-06cf-41fa-ad98-7258b70c2a72/buildId/$($Env:BUILD_BUILDID)/artifactName/Release"
    $path = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($rawpath))
    $jar = "twilightforest-$($env:JAVAPROPS_MINECRAFT_SUB_VERSION)-$($env:JAVAPROPS_MOD_VERSION).$($env:REVISION)-universal.jar"
    $downloadUrl = "https://artprodcus3.artifacts.visualstudio.com/Abaabfa6c-deea-4587-ba05-c308c2597b7a/1ef09d39-06cf-41fa-ad98-7258b70c2a72/_apis/artifact/$($path)0/content?format=file&subPath=%2F$($jar)"
    $jobResult = (Get-Culture).TextInfo.ToTitleCase(${env:agent.jobstatus})
    $Colour = 65280
    if ($jobResult -ne "Succeeded") {
      $Colour = 16711680
    }
    Write-Host "##vso[task.setvariable variable=DiscordMessageColour]$Colour"

    $json = [Ordered]@{
        title = "Build $jobResult"
        url = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)Twilight%20Forest/_build/results?buildId=$($Env:BUILD_BUILDID)&view=results"
        color = $Colour
        fields = (
            [Ordered]@{
                name = "Author"
                value = "$($env:BUILD_SOURCEVERSIONAUTHOR)"
            },
            [Ordered]@{
                name = "Minecraft Version"
                value = "$($env:JAVAPROPS_MINECRAFT_SUB_VERSION)"
            },
            [Ordered]@{
                name = "Mod Version"
                value = "$($env:JAVAPROPS_MOD_VERSION).$($env:REVISION)"
            },
            [Ordered]@{
                name = "Forge Version"
                value = "$($env:JAVAPROPS_FORGE_VERSION)"
            },
            [Ordered]@{
                name = "Commit"
                value = "[$(($env:BUILD_SOURCEVERSION).Substring(0, 6))]$($env:BUILD_REPOSITORY_URI)/commit/$($env:BUILD_SOURCEVERSION)"
            }
        )
    }
    if ($jobResult -eq "Succeeded") {
        $json["fields"] += [Ordered]@{
            name = "Download"
            value = "$downloadUrl"
        }
    }
    Write-Host "##vso[task.setvariable variable=DiscordMessage]$($json | ConvertTo-Json -Compress)"
  displayName: Format discord message
  condition: always()
  env:
    SYSTEM_ACCESSTOKEN: $(System.AccessToken)
    
- task: ado-discord-webhook@1
  displayName: Announce Build to discord
  inputs:
    channelId: '$(DiscordChannelID)'
    webhookKey: '$(DiscordChannelSecret)'
    messageType: 'embeds'
    embeds: |
      [$(DiscordMessage)]
  condition: and(always(), eq(variables['CreateArtifacts'], 'True'))

- task: Gradle@2
  displayName: Publish to Maven
  inputs:
    workingDirectory: ''
    options: '-PCIRevision=$(javaprops_mod_version).$(revision) -PCIType=RELEASE'
    gradleWrapperFile: 'gradlew'
    gradleOptions: '-Xmx3072m'
    javaHomeOption: 'JDKVersion'
    jdkVersionOption: '1.8'
    jdkArchitectureOption: 'x64'
    publishJUnitResults: false
    testResultsFiles: '**/TEST-*.xml'
    tasks: 'publish'
  condition: and(succeeded(), eq(variables['CreateArtifacts'], 'True'))
  env:
    ARTIFACTORY_USER: $(Artifactory.User)
    ARTIFACTORY_PASS: $(Artifactory.Password)

- script: |
    # stop the Gradle daemon to ensure no files are left open (impacting the save cache operation later)
    ./gradlew --stop
  displayName: Kill Daemon
