steps:
  - task: NodeTool@0
    inputs:
      versionSpec: "16.x"

  - 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
      sudo apt-get install -y curl apt-transport-https ca-certificates

      # Yarn
      curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
      echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
      sudo apt-get update
      sudo apt-get install -y yarn

      # 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 prime $SNAPCRAFT_TARGET_ARGS && snap pack prime --compression=lzo --filename="$SNAP_PATH")

      # Export SNAP_PATH
      echo "##vso[task.setvariable variable=SNAP_PATH]$SNAP_PATH"
    displayName: Prepare for publish

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