parameters:
  - name: branding
    type: string
  - name: buildConfigurations
    type: object
  - name: buildPlatforms
    type: object
  - name: generateSbom
    type: boolean
    default: false
  - name: codeSign
    type: boolean
    default: false
  - name: pool
    type: object
    default: []
  - name: dependsOn
    type: object
    default: null
  - name: artifactStem
    type: string
    default: ''
  - name: jobName
    type: string
    default: Bundle
  - name: variables
    type: object
    default: {}
  - name: publishArtifacts
    type: boolean
    default: true
  - name: afterBuildSteps
    type: stepList
    default: []
  - name: signingIdentity
    type: object
    default: {}

jobs:
- job: ${{ parameters.jobName }}
  ${{ if ne(length(parameters.pool), 0) }}:
    pool: ${{ parameters.pool }}
  ${{ if eq(parameters.codeSign, true) }}:
    displayName: Pack and Sign Terminal MSIXBundle
  ${{ else }}:
    displayName: Pack Terminal MSIXBundle
  strategy:
    matrix:
      ${{ each config in parameters.buildConfigurations }}:
        ${{ config }}:
          BuildConfiguration: ${{ config }}
  variables:
    ${{ if eq(parameters.branding, 'Release') }}:
      BundleStemName: Microsoft.WindowsTerminal
    ${{ elseif eq(parameters.branding, 'Preview') }}:
      BundleStemName: Microsoft.WindowsTerminalPreview
    ${{ elseif eq(parameters.branding, 'Canary') }}:
      BundleStemName: Microsoft.WindowsTerminalCanary
    ${{ else }}:
      BundleStemName: WindowsTerminalDev
    JobOutputDirectory: '$(System.ArtifactsDirectory)/bundle'
    JobOutputArtifactName: appxbundle-$(BuildConfiguration)${{ parameters.artifactStem }}
    ${{ insert }}: ${{ parameters.variables }}
  dependsOn: ${{ parameters.dependsOn }}
  steps:
  - checkout: self
    clean: true
    fetchDepth: 1
    fetchTags: false # Tags still result in depth > 1 fetch; we don't need them here
    submodules: true
    persistCredentials: True

  - template: steps-setup-versioning.yml

  - template: steps-download-bin-dir-artifact.yml
    parameters:
      buildPlatforms: ${{ parameters.buildPlatforms }}
      # This build is already matrix'd on configuration, so
      # just pass a single config into the download template.
      buildConfigurations:
        - $(BuildConfiguration)
      artifactStem: ${{ parameters.artifactStem }}

  # Add 3000 to the major version component, but only for the bundle.
  # This is to ensure that it is newer than "2022.xx.yy.zz" or whatever the original bundle versions were before
  # we switched to uniform naming.
  - pwsh: |-
      $VersionEpoch = 3000
      $Components = "$(XES_APPXMANIFESTVERSION)" -Split "\."
      $Components[0] = ([int]$Components[0] + $VersionEpoch)
      $BundleVersion = $Components -Join "."
      New-Item -Type Directory "$(System.ArtifactsDirectory)/bundle"
      $BundlePath = "$(System.ArtifactsDirectory)\bundle\$(BundleStemName)_$(XES_APPXMANIFESTVERSION)_8wekyb3d8bbwe.msixbundle"
      .\build\scripts\Create-AppxBundle.ps1 -InputPath 'bin/' -ProjectName CascadiaPackage -BundleVersion $BundleVersion -OutputPath $BundlePath
      Write-Host "##vso[task.setvariable variable=MsixBundlePath]${BundlePath}"
    displayName: Create msixbundle

  - ${{ if eq(parameters.codeSign, true) }}:
    - template: steps-esrp-signing.yml
      parameters:
        displayName: Submit *.msixbundle to ESRP for code signing
        signingIdentity: ${{ parameters.signingIdentity }}
        inputs:
          FolderPath: $(System.ArtifactsDirectory)\bundle
          Pattern: $(BundleStemName)*.msixbundle
          UseMinimatch: true
          signConfigType: inlineSignParams
          inlineOperation: >-
            [
                {
                    "KeyCode": "Dynamic",
                    "CertTemplateName": "WINMSAPP1ST",
                    "CertSubjectName": "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US",
                    "OperationCode": "SigntoolSign",
                    "Parameters": {
                        "OpusName": "Microsoft",
                        "OpusInfo": "http://www.microsoft.com",
                        "FileDigest": "/fd \"SHA256\"",
                        "TimeStamp": "/tr \"http://rfc3161.gtm.corp.microsoft.com/TSS/HttpTspServer\" /td sha256"
                    },
                    "ToolName": "sign",
                    "ToolVersion": "1.0"
                },
                {
                    "KeyCode": "Dynamic",
                    "CertTemplateName": "WINMSAPP1ST",
                    "CertSubjectName": "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US",
                    "OperationCode": "SigntoolVerify",
                    "Parameters": {},
                    "ToolName": "sign",
                    "ToolVersion": "1.0"
                }
            ]

  - ${{ if eq(parameters.generateSbom, true) }}:
    - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0
      displayName: 'Generate SBOM manifest (bundle)'
      inputs:
       BuildDropPath: '$(System.ArtifactsDirectory)/bundle'
       BuildComponentPath: '$(Build.SourcesDirectory)/bin'

    - task: DropValidatorTask@0
      displayName: 'Validate bundle SBOM manifest'
      inputs:
        BuildDropPath: '$(System.ArtifactsDirectory)/bundle'
        OutputPath: 'output.json'
        ValidateSignature: true
        Verbosity: 'Verbose'

  - ${{ parameters.afterBuildSteps }}

  - ${{ if eq(parameters.publishArtifacts, true) }}:
    - publish: $(JobOutputDirectory)
      artifact: $(JobOutputArtifactName)
      displayName: Publish msixbundle
