#################################################################################
#                           Onebranch Retail Pipeline                           #
# This pipeline was created by EasyStart from a sample located at:              #
#   https://aka.ms/obpipelines/easystart/samples                                #
# Documentation:  https://aka.ms/obpipelines                                    #
# Yaml Schema:    https://aka.ms/obpipelines/yaml/schema                        #
# Retail Tasks:   https://aka.ms/obpipelines/tasks                              #
# Support:        https://aka.ms/onebranchsup                                   #
#################################################################################

trigger: none # https://aka.ms/obpipelines/triggers

parameters: # parameters are shown up in ADO UI in a build queue time
  - name: "debug"
    displayName: "Enable debug output"
    type: boolean
    default: false

variables:
  - name: CDP_DEFINITION_BUILD_COUNT
    value: $[counter('', 0)] # needed for onebranch.pipeline.version task https://aka.ms/obpipelines/versioning
  - name: system.debug
    value: ${{ parameters.debug }}
  - name: WindowsContainerImage
    value: "onebranch.azurecr.io/windows/ltsc2019/vse2022:latest" # Docker image which is used to build the project https://aka.ms/obpipelines/containers
  - name: LinuxContainerImage
    value: "mcr.microsoft.com/onebranch/azurelinux/build:3.0"

resources:
  repositories:
    - repository: templates
      type: git
      name: OneBranch.Pipelines/GovernedTemplates
      ref: refs/heads/main

extends: # Governed template expands from here which defines over all pipeline orchestration with OneBranch security, Compliance & Governance enabled
  template: v2/OneBranch.Official.CrossPlat.yml@templates # The Official template may only be used by Production-classified pipelines
  parameters:
    git:
      fetchDepth: 1

    featureFlags:
      LinuxHostVersion:
        Network: KS1
      WindowsHostVersion:
        Network: KS1
      linuxEsrpSigning: true

    cloudvault: # https://aka.ms/obpipelines/cloudvault
      enabled: false
    globalSdl: # https://aka.ms/obpipelines/sdl
      tsa:
        enabled: false # onebranch publish all sdl results to TSA. If TSA is disabled all SDL tools will forced into 'break' build mode.
      policheck:
        break: true # always break the build on policheck issues. You can disable it by setting to 'false'
      perStage:
        sdl_sources:
          checkout_all_repos: true

    stages:
      - stage: Build
        jobs:
          - job: initialize_build
            pool:
              type: linux

            variables:
              ob_outputDirectory: "$(Build.ArtifactStagingDirectory)" # REQUIRED even if not used: this directory is uploaded to pipeline artifacts, reddog and cloudvault. More info at https://aka.ms/obpipelines/artifacts

            steps:
              - task: onebranch.pipeline.version@1 # generates automatic version. For other versioning options check https://aka.ms/obpipelines/versioning
                displayName: "Setup Build Number"
                inputs:
                  system: "RevisionCounter"
                  major: "1"
                  minor: "0"
                  exclude_commit: true
                enabled: true

          - job: build_extension

            pool:
              type: linux

            variables:
              ob_git_checkout: true
              ob_outputDirectory: "$(Build.ArtifactStagingDirectory)" # REQUIRED even if not used: this directory is uploaded to pipeline artifacts, reddog and cloudvault. More info at https://aka.ms/obpipelines/artifacts

            steps:
              - template: .pipelines/templates/include-build.yml@self

      - stage: Release
        dependsOn:
        - Build
        jobs:
          - job: release_preparation
            displayName: Prepare Release (GitHub + metadata)
            pool:
              type: linux

            variables:
              ob_outputDirectory: "$(Build.ArtifactStagingDirectory)"

            steps:
              - bash: |
                  if [[ "$BUILD_SOURCEBRANCH" == refs/tags/* ]]; then
                    TAG_NAME=${BUILD_SOURCEBRANCH#refs/tags/}
                    # Set as both job variable and output variable
                    echo "##vso[task.setvariable variable=ReleaseVersion]$TAG_NAME"
                    echo "##vso[task.setvariable variable=ReleaseVersion;isOutput=true]$TAG_NAME"
                    echo "Release triggered from tag: $TAG_NAME"
                  else
                    echo "ERROR: Release pipeline must be triggered from a git tag" >&2
                    echo "Current BUILD_SOURCEBRANCH: $BUILD_SOURCEBRANCH" >&2
                    echo "Expected format: refs/tags/v1.2.3 or refs/tags/v1.2.3-dev.1" >&2
                    exit 1
                  fi
                name: captureVersion
                displayName: Get Release Version

              - bash: |
                  if echo "$(ReleaseVersion)" | grep -q -- "-dev"; then
                    echo "##vso[task.setvariable variable=IsDevTag]true"
                    echo "##vso[task.setvariable variable=IsDevTag;isOutput=true]true"
                    echo "##vso[task.setvariable variable=GitHubIsPrerelease]true"
                    echo "This is a dev release - will skip manual validation"
                  else
                    echo "##vso[task.setvariable variable=IsDevTag]false"
                    echo "##vso[task.setvariable variable=IsDevTag;isOutput=true]false"
                    echo "##vso[task.setvariable variable=GitHubIsPrerelease]false"
                    echo "This is a production release - will require manual validation"
                  fi
                name: determineReleaseType
                displayName: Determine Release Type

              - template: .pipelines/templates/include-github-release.yml@self

              - bash: |
                  if [ "$(IsDevTag)" = "true" ]; then
                    echo "Dev release detected - skipping marketplace type calculation."
                    echo "##vso[task.setvariable variable=MarketplaceReleaseType;isOutput=true]DEV"
                    echo "##vso[task.setvariable variable=VscePreReleaseFlag;isOutput=true]"
                    exit 0
                  fi

                  TAG_NAME=$(echo "$(ReleaseVersion)" | sed 's/^v//')
                  MINOR=$(echo "$TAG_NAME" | cut -d. -f2 | cut -d- -f1)

                  echo "Release version: $(ReleaseVersion)"
                  echo "Minor version: $MINOR"

                  if [[ "$MINOR" =~ ^[0-9]+$ ]]; then
                    if (( MINOR % 2 == 1 )); then
                      echo "##vso[task.setvariable variable=MarketplaceReleaseType;isOutput=true]PRE-RELEASE"
                      echo "##vso[task.setvariable variable=VscePreReleaseFlag;isOutput=true]--pre-release"
                      echo "This will be published as a PRE-RELEASE (odd minor: $MINOR)"
                    else
                      echo "##vso[task.setvariable variable=MarketplaceReleaseType;isOutput=true]STABLE"
                      echo "##vso[task.setvariable variable=VscePreReleaseFlag;isOutput=true]"
                      echo "This will be published as a STABLE release (even minor: $MINOR)"
                    fi
                  else
                    echo "ERROR: Invalid version format - minor version '$MINOR' is not numeric" >&2
                    echo "Expected format: vMAJOR.MINOR.PATCH (e.g., v1.2.3 or v1.3.0-dev.1)" >&2
                    exit 1
                  fi
                name: marketplaceInfo
                displayName: Determine Marketplace Release Type

          # Manual validation gate - only blocks Marketplace publication for production releases
          - job: waitForMarketplaceValidation
            displayName: Wait for Marketplace validation
            dependsOn:
            - release_preparation
            pool:
              type: agentless # ManualValidation must run on an agentless pool.
            timeoutInMinutes: 360
            # Only require validation for non-dev releases
            condition: and(succeeded(), eq(dependencies.release_preparation.outputs['determineReleaseType.IsDevTag'], 'false'))
            variables:
              ReleaseVersion: $[ dependencies.release_preparation.outputs['captureVersion.ReleaseVersion'] ]
              MarketplaceReleaseType: $[ dependencies.release_preparation.outputs['marketplaceInfo.MarketplaceReleaseType'] ]
            steps:
              - task: ManualValidation@0
                displayName: "Confirm Marketplace release"
                inputs:
                  notifyUsers: |
                    mmcfarland@microsoft.com
                    robemanuele@microsoft.com
                    prateesingh@microsoft.com
                    mihirmallya@microsoft.com
                  instructions: |
                    ⚠️ IMPORTANT: Please validate this release for VS Code Marketplace publication.

                    Release Version: $(ReleaseVersion)
                    Release Type: $(MarketplaceReleaseType)

                    The GitHub release has already been created.

                    ✅ Approving this validation will trigger a $(MarketplaceReleaseType) Marketplace publication.
                    ❌ Rejecting or timing out will skip Marketplace publication.
                  onTimeout: "reject"

          # Marketplace publication requires manual approval - ONLY for production releases
          - job: marketplace_release
            displayName: Marketplace Release
            dependsOn:
            - release_preparation
            - waitForMarketplaceValidation
            # Only run for production releases (IsDevTag == false) after validation succeeds
            condition: |
              and(
                eq(dependencies.release_preparation.outputs['determineReleaseType.IsDevTag'], 'false'),
                eq(dependencies.release_preparation.result, 'Succeeded'),
                eq(dependencies.waitForMarketplaceValidation.result, 'Succeeded')
              )
            pool:
              type: linux

            variables:
              ob_outputDirectory: "$(Build.ArtifactStagingDirectory)"
              ReleaseVersion: $[ dependencies.release_preparation.outputs['captureVersion.ReleaseVersion'] ]
              IsDevTag: $[ dependencies.release_preparation.outputs['determineReleaseType.IsDevTag'] ]
              VscePreReleaseFlag: $[ dependencies.release_preparation.outputs['marketplaceInfo.VscePreReleaseFlag'] ]
              MarketplaceReleaseType: $[ dependencies.release_preparation.outputs['marketplaceInfo.MarketplaceReleaseType'] ]

            steps:
              - template: .pipelines/templates/include-marketplace-release.yml@self
