# Copyright 2016-2020 the Tectonic Project
# Licensed under the MIT License.
#
# Generic setup in the deployment stage. The main goal is to recover the Cranko
# `release` commit. We assume that we are running on Linux.

parameters:
- name: setupGit
  type: boolean
  default: false
- name: isMainDev
  type: boolean
  default: false
- name: isRelease
  type: boolean
  default: false

steps:
- download: current

- checkout: self
  submodules: true

- bash: |
    set -xeuo pipefail
    git switch -c release
    git pull --ff-only $(Pipeline.Workspace)/git-release/release.bundle
    git show
  displayName: Restore release commit

- bash: |
    set -euo pipefail
    d="$(mktemp -d /tmp/cranko.XXXXXX)"
    cd "$d"
    curl --proto '=https' --tlsv1.2 -sSf https://pkgw.github.io/cranko/fetch-latest.sh | sh
    echo "##vso[task.prependpath]$d"
  displayName: Install latest Cranko

# We determine a "toplevel" release mode that affects things like updates to the
# book. The $TOPLEVEL_MODE variabe has three settings:
#
# - "latest" if this is continuous deployment/delivery, i.e. a push to the
#   `master` branch. In this case we update things like the book under the
#   version code "latest"
# - "skip" if this is an RC update that does *not* update the main `tectonic`
#   project. In this case we do not update things.
# - Otherwise, the text of the variable is the version string of a new official
#   release of the `tectonic` project. Things like the book should be updated
#   with a real version number.
#
# The boolean parameters stringify to `True` or `False`
- bash: |
    set -xeuo pipefail
    if [[ ${isMainDev} == True ]] ; then
      version_text=latest
    elif cranko show if-released --exit-code tectonic ; then
      version_text="$(cranko show version tectonic)"
    else
      version_text=skip
    fi

    echo "toplevel version: $isMainDev, $isRelease => $version_text"

    # `set -x` messes up `setvariable` behavior:
    set +x
    echo "##vso[task.setvariable variable=TOPLEVEL_MODE;]$version_text"
  displayName: Set toplevel release mode
  env:
    isMainDev: ${{ parameters.isMainDev }}
    isRelease: ${{ parameters.isRelease }}

- ${{ if parameters.setupGit }}:
  - bash: |
      set -xeuo pipefail
      cranko github install-credential-helper
      git config --global user.email "notifications@github.com"
      git config --global user.name "Tectonic CI"
    displayName: Set up Git actions
    env:
      GITHUB_TOKEN: $(GITHUB_TOKEN)
