name: Nightly Snapshot Release

on:
  schedule:
    - cron: '0 2 * * *' # run at 2 AM UTC

jobs:
  build:
    if: github.repository == 'backstage/backstage' # prevent running on forks

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [14.x]

    env:
      CI: true
      NODE_OPTIONS: --max-old-space-size=4096

    steps:
      - uses: actions/checkout@v2

      # Beginning of yarn setup, keep in sync between all workflows, see ci.yml
      - name: use node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}
          registry-url: https://registry.npmjs.org/ # Needed for auth
      - name: cache all node_modules
        id: cache-modules
        uses: actions/cache@v2
        with:
          path: '**/node_modules'
          key: ${{ runner.os }}-v${{ matrix.node-version }}-node_modules-${{ hashFiles('yarn.lock', '**/package.json') }}
      - name: find location of global yarn cache
        id: yarn-cache
        if: steps.cache-modules.outputs.cache-hit != 'true'
        run: echo "::set-output name=dir::$(yarn cache dir)"
      - name: cache global yarn cache
        uses: actions/cache@v2
        if: steps.cache-modules.outputs.cache-hit != 'true'
        with:
          path: ${{ steps.yarn-cache.outputs.dir }}
          key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}
          restore-keys: |
            ${{ runner.os }}-yarn-
      - name: yarn install
        run: yarn install --frozen-lockfile
      # End of yarn setup

      # No verification done here, only build & publish. If the master branch
      # is broken we will see that from those builds, but we still want to push nightly
      # builds since upgrading to them is a manual process anyway.

      - name: tsc
        run: yarn tsc
      - name: build
        run: yarn build

      # Prepares a nightly release version of any package with pending changesets
      - name: prepare nightly release
        run: yarn changeset version --snapshot nightly

      # Publishes the nightly release to NPM, by using tag we make sure the release is
      # not flagged as the latest release, which means that people will not get this
      # version of the package unless requested explicitly
      - name: publish nightly release
        run: yarn changeset publish --tag nightly
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Discord notification
        if: ${{ failure() }}
        uses: Ilshidur/action-discord@0.2.0
        env:
          DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
        with:
          args: 'Nightly build failed https://github.com/{{GITHUB_REPOSITORY}}/actions/runs/{{GITHUB_RUN_ID}}'
