name: <%= workflowName %>

trigger:
  - <%= mainBranch %>
pr:
  - <%= mainBranch %>

variables:
  CI: 'true'
  NX_CLOUD_DISTRIBUTED_EXECUTION: 'true'
  ${{ if eq(variables['Build.Reason'], 'PullRequest') }}:
    NX_BRANCH: $(System.PullRequest.PullRequestNumber)
    TARGET_BRANCH: $[replace(variables['System.PullRequest.TargetBranch'],'refs/heads/','origin/')]
    BASE_SHA: $(git merge-base $(TARGET_BRANCH) HEAD)
  ${{ if ne(variables['Build.Reason'], 'PullRequest') }}:
    NX_BRANCH: $(Build.SourceBranchName)
    BASE_SHA: $(git rev-parse HEAD~1)
  HEAD_SHA: $(git rev-parse HEAD)

jobs:
  - job: agents
    strategy:
      parallel: 3
    displayName: Nx Cloud Agent
    pool:
      vmImage: 'ubuntu-latest'
    steps:
      <% if(packageManagerPrefix == 'pnpm exec'){ %>
      - script: npm install --prefix=$HOME/.local -g pnpm@6.32.4
        displayName: Install PNPM
      <% } %>- script: <%= packageManagerInstall %>
        displayName: NPM Install Dependencies
      - script: npx nx-cloud start-agent
        displayName: Start Nx-Cloud agent

  - job: main
    displayName: Nx Cloud Main
    pool:
      vmImage: 'ubuntu-latest'
    steps:
      <% if(packageManagerPrefix == 'pnpm exec'){ %>
      - script: npm install --prefix=$HOME/.local -g pnpm@6.32.4
        displayName: Install PNPM
      <% } %>- script: <%= packageManagerInstall %>
        displayName: NPM Install Dependencies
      - script: <%= packageManagerPrefix %> nx-cloud start-ci-run --stop-agents-after="build" --agent-count=3
        displayName: Start CI run
      - script: <%= packageManagerPrefix %> nx-cloud record -- <%= packageManagerPrefix %> nx format:check --base=$(BASE_SHA) --head=$(HEAD_SHA)
        displayName: Check format
      - script: <%= packageManagerPrefix %> nx affected --base=$(BASE_SHA) --head=$(HEAD_SHA) --target=lint --parallel=3
        displayName: Run lint
      - script: <%= packageManagerPrefix %> nx affected --base=$(BASE_SHA) --head=$(HEAD_SHA) --target=test --parallel=3 --ci --code-coverage
        displayName: Run test
      - script: <%= packageManagerPrefix %> nx affected --base=$(BASE_SHA) --head=$(HEAD_SHA) --target=build --parallel=3
        displayName: Run build
      - script: <%= packageManagerPrefix %> nx-cloud stop-all-agents
        condition: always()
        displayName: Stop all Nx-Cloud agents
