parameters:
  - name: VSCODE_ARCH
    type: string

jobs:
  - job: Alpine_${{ parameters.VSCODE_ARCH }}
    displayName: Alpine (${{ upper(parameters.VSCODE_ARCH) }})
    timeoutInMinutes: 30
    pool:
      name: 1es-ubuntu-22.04-x64
      os: linux
    variables:
      NPM_ARCH: ${{ parameters.VSCODE_ARCH }}
      VSCODE_ARCH: ${{ parameters.VSCODE_ARCH }}
    templateContext:
      outputParentDirectory: $(Build.ArtifactStagingDirectory)/out
      outputs:
        - ${{ if eq(parameters.VSCODE_ARCH, 'x64') }}:
          # keep legacy name
          - output: pipelineArtifact
            targetPath: $(Build.ArtifactStagingDirectory)/out/server/vscode-server-linux-alpine.tar.gz
            artifactName: vscode_server_linux_alpine_archive-unsigned
            displayName: Publish x64 server archive
            sbomBuildDropPath: $(SERVER_DIR_PATH)
            sbomPackageName: "VS Code Alpine x64 Server"
            sbomPackageVersion: $(Build.SourceVersion)
          # keep legacy name
          - output: pipelineArtifact
            targetPath: $(Build.ArtifactStagingDirectory)/out/web/vscode-server-linux-alpine-web.tar.gz
            artifactName: vscode_web_linux_alpine_archive-unsigned
            displayName: Publish x64 web server archive
            sbomBuildDropPath: $(WEB_DIR_PATH)
            sbomPackageName: "VS Code Alpine x64 Web"
            sbomPackageVersion: $(Build.SourceVersion)
        - ${{ if ne(parameters.VSCODE_ARCH, 'x64') }}:
          - output: pipelineArtifact
            targetPath: $(Build.ArtifactStagingDirectory)/out/server/vscode-server-alpine-$(VSCODE_ARCH).tar.gz
            artifactName: vscode_server_alpine_$(VSCODE_ARCH)_archive-unsigned
            displayName: Publish server archive
            sbomBuildDropPath: $(SERVER_DIR_PATH)
            sbomPackageName: "VS Code Alpine $(VSCODE_ARCH) Server"
            sbomPackageVersion: $(Build.SourceVersion)
          - output: pipelineArtifact
            targetPath: $(Build.ArtifactStagingDirectory)/out/web/vscode-server-alpine-$(VSCODE_ARCH)-web.tar.gz
            artifactName: vscode_web_alpine_$(VSCODE_ARCH)_archive-unsigned
            displayName: Publish web server archive
            sbomBuildDropPath: $(WEB_DIR_PATH)
            sbomPackageName: "VS Code Alpine $(VSCODE_ARCH) Web"
            sbomPackageVersion: $(Build.SourceVersion)
    steps:
      - template: ../common/checkout.yml@self

      - task: NodeTool@0
        inputs:
          versionSource: fromFile
          versionFilePath: .nvmrc

      - template: ../distro/download-distro.yml@self

      - task: AzureKeyVault@2
        displayName: "Azure Key Vault: Get Secrets"
        inputs:
          azureSubscription: vscode
          KeyVaultName: vscode-build-secrets
          SecretsFilter: "github-distro-mixin-password"

      - script: node build/setup-npm-registry.ts $NPM_REGISTRY
        condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none'))
        displayName: Setup NPM Registry

      - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.ts alpine $VSCODE_ARCH $(node -p process.arch) > .build/packagelockhash
        displayName: Prepare node_modules cache key

      - task: Cache@2
        inputs:
          key: '"node_modules" | .build/packagelockhash'
          path: .build/node_modules_cache
          cacheHitVar: NODE_MODULES_RESTORED
        displayName: Restore node_modules cache

      - script: tar -xzf .build/node_modules_cache/cache.tgz
        condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true'))
        displayName: Extract node_modules cache

      - script: |
          set -e
          # Set the private NPM registry to the global npmrc file
          # so that authentication works for subfolders like build/, remote/, extensions/ etc
          # which does not have their own .npmrc file
          npm config set registry "$NPM_REGISTRY"
          echo "##vso[task.setvariable variable=NPMRC_PATH]$(npm config get userconfig)"
        condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none'))
        displayName: Setup NPM

      - task: npmAuthenticate@0
        inputs:
          workingFile: $(NPMRC_PATH)
        condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none'))
        displayName: Setup NPM Authentication

      - task: Docker@1
        inputs:
          azureSubscriptionEndpoint: vscode
          azureContainerRegistry: vscodehub.azurecr.io
          command: "Run an image"
          imageName: "vscode-linux-build-agent:alpine-$(VSCODE_ARCH)"
          containerCommand: uname
        displayName: "Pull image"
        condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))

      - script: sudo apt-get update && sudo apt-get install -y libkrb5-dev
        displayName: Install build dependencies
        condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))

      - script: |
          set -e
          mkdir -p .build/nodejs-musl
          NODE_VERSION=$(grep '^target=' remote/.npmrc | cut -d '"' -f 2)
          BUILD_ID=$(grep '^ms_build_id=' remote/.npmrc | cut -d '"' -f 2)
          gh release download "v${NODE_VERSION}-${BUILD_ID}" -R microsoft/vscode-node -p "node-v${NODE_VERSION}-linux-${VSCODE_ARCH}-musl.tar.gz" --dir .build/nodejs-musl --clobber
          tar -xzf ".build/nodejs-musl/node-v${NODE_VERSION}-linux-${VSCODE_ARCH}-musl.tar.gz" -C ".build/nodejs-musl" --strip-components=1
          rm ".build/nodejs-musl/node-v${NODE_VERSION}-linux-${VSCODE_ARCH}-musl.tar.gz"
        env:
          GITHUB_TOKEN: "$(github-distro-mixin-password)"
        displayName: Download NodeJS MUSL
        condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))

      - script: |
          set -e

          for i in {1..5}; do # try 5 times
            npm ci && break
            if [ $i -eq 5 ]; then
              echo "Npm install failed too many times" >&2
              exit 1
            fi
            echo "Npm install failed $i, trying again..."
          done
        env:
          npm_config_arch: $(NPM_ARCH)
          ELECTRON_SKIP_BINARY_DOWNLOAD: 1
          PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
          GITHUB_TOKEN: "$(github-distro-mixin-password)"
          VSCODE_REMOTE_DEPENDENCIES_CONTAINER_NAME: vscodehub.azurecr.io/vscode-linux-build-agent:alpine-$(VSCODE_ARCH)
          VSCODE_HOST_MOUNT: "/mnt/vss/_work/1/s"
          VSCODE_NPMRC_PATH: $(NPMRC_PATH)
        displayName: Install dependencies
        condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))

      - script: node build/azure-pipelines/distro/mixin-npm.ts
        displayName: Mixin distro node modules
        condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))

      - script: |
          set -e
          node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt
          mkdir -p .build/node_modules_cache
          tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt
        condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))
        displayName: Create node_modules archive

      - script: node build/azure-pipelines/distro/mixin-quality.ts
        displayName: Mixin distro quality

      - template: ../common/install-builtin-extensions.yml@self

      - script: npm run gulp core-ci
        env:
          GITHUB_TOKEN: "$(github-distro-mixin-password)"
        displayName: Compile

      - script: |
          set -e
          TARGET=$([ "$VSCODE_ARCH" == "x64" ] && echo "linux-alpine" || echo "alpine-arm64") # TODO@joaomoreno
          npm run gulp vscode-reh-$TARGET-min-ci
          (cd .. && mv vscode-reh-$TARGET vscode-server-$TARGET) # TODO@joaomoreno
          ARCHIVE_PATH="$(Build.ArtifactStagingDirectory)/out/server/vscode-server-$TARGET.tar.gz"
          DIR_PATH="$(realpath ../vscode-server-$TARGET)"
          mkdir -p $(dirname $ARCHIVE_PATH)
          tar --owner=0 --group=0 -czf $ARCHIVE_PATH -C .. vscode-server-$TARGET
          echo "##vso[task.setvariable variable=SERVER_DIR_PATH]$DIR_PATH"
          echo "##vso[task.setvariable variable=SERVER_PATH]$ARCHIVE_PATH"
        env:
          GITHUB_TOKEN: "$(github-distro-mixin-password)"
        displayName: Build server

      - script: |
          set -e
          TARGET=$([ "$VSCODE_ARCH" == "x64" ] && echo "linux-alpine" || echo "alpine-arm64")
          npm run gulp vscode-reh-web-$TARGET-min-ci
          (cd .. && mv vscode-reh-web-$TARGET vscode-server-$TARGET-web) # TODO@joaomoreno
          ARCHIVE_PATH="$(Build.ArtifactStagingDirectory)/out/web/vscode-server-$TARGET-web.tar.gz"
          DIR_PATH="$(realpath ../vscode-server-$TARGET-web)"
          mkdir -p $(dirname $ARCHIVE_PATH)
          tar --owner=0 --group=0 -czf $ARCHIVE_PATH -C .. vscode-server-$TARGET-web
          echo "##vso[task.setvariable variable=WEB_DIR_PATH]$DIR_PATH"
          echo "##vso[task.setvariable variable=WEB_PATH]$ARCHIVE_PATH"
        env:
          GITHUB_TOKEN: "$(github-distro-mixin-password)"
        displayName: Build server (web)
