steps:
  - task: NodeTool@0
    inputs:
      versionSpec: "12.18.3"

  - task: geeklearningio.gl-vsts-tasks-yarn.yarn-installer-task.YarnInstaller@2
    inputs:
      versionSpec: "1.x"

  - task: AzureKeyVault@1
    displayName: "Azure Key Vault: Get Secrets"
    inputs:
      azureSubscription: "vscode-builds-subscription"
      KeyVaultName: vscode

  - task: DownloadPipelineArtifact@0
    displayName: "Download Pipeline Artifact"
    inputs:
      artifactName: snap-$(VSCODE_ARCH)
      targetPath: .build/linux/snap-tarball

  - script: |
      set -e

      # Get snapcraft version
      snapcraft --version

      # Make sure we get latest packages
      sudo apt-get update
      sudo apt-get upgrade -y

      # Define variables
      REPO="$(pwd)"
      SNAP_ROOT="$REPO/.build/linux/snap/$(VSCODE_ARCH)"

      # Install build dependencies
      (cd build && yarn)

      # Unpack snap tarball artifact, in order to preserve file perms
      SNAP_TARBALL_PATH="$REPO/.build/linux/snap-tarball/snap-$(VSCODE_ARCH).tar.gz"
      (cd .build/linux && tar -xzf $SNAP_TARBALL_PATH)

      # Create snap package
      BUILD_VERSION="$(date +%s)"
      SNAP_FILENAME="code-$VSCODE_QUALITY-$(VSCODE_ARCH)-$BUILD_VERSION.snap"
      SNAP_PATH="$SNAP_ROOT/$SNAP_FILENAME"
      case $(VSCODE_ARCH) in
        x64) SNAPCRAFT_TARGET_ARGS="" ;;
        *) SNAPCRAFT_TARGET_ARGS="--target-arch $(VSCODE_ARCH)" ;;
      esac
      (cd $SNAP_ROOT/code-* && sudo --preserve-env snapcraft snap $SNAPCRAFT_TARGET_ARGS --output "$SNAP_PATH")

      # Publish snap package
      AZURE_DOCUMENTDB_MASTERKEY="$(builds-docdb-key-readwrite)" \
      AZURE_STORAGE_ACCESS_KEY_2="$(vscode-storage-key)" \
      node build/azure-pipelines/common/createAsset.js "linux-snap-$(VSCODE_ARCH)" package "$SNAP_FILENAME" "$SNAP_PATH"

      # Export SNAP_PATH
      echo "##vso[task.setvariable variable=SNAP_PATH]$SNAP_PATH"

  - publish: $(SNAP_PATH)
    artifact: vscode-linux-snap-$(VSCODE_ARCH)
    displayName: Publish snap package
    condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false'))