name: (Runtime) Publish Prereleases

on:
  workflow_call:
    inputs:
      commit_sha:
        required: true
        default: ''
        type: string
      release_channel:
        required: true
        type: string
      dist_tag:
        required: true
        type: string
      enableFailureNotification:
        description: 'Whether to notify the team on Discord when the release fails. Useful if this workflow is called from an automation.'
        required: false
        type: boolean
    secrets:
      DISCORD_WEBHOOK_URL:
        description: 'Discord webhook URL to notify on failure. Only required if enableFailureNotification is true.'
        required: false
      GH_TOKEN:
        required: true
      NPM_TOKEN:
        required: true

permissions: {}

env:
  TZ: /usr/share/zoneinfo/America/Los_Angeles
  # https://github.com/actions/cache/blob/main/tips-and-workarounds.md#cache-segment-restore-timeout
  SEGMENT_DOWNLOAD_TIMEOUT_MINS: 1
  NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

jobs:
  publish_prerelease:
    name: Publish prelease (${{ inputs.release_channel }}) ${{ inputs.commit_sha }} @${{ inputs.dist_tag }}
    runs-on: ubuntu-latest
    permissions:
      # We use github.token to download the build artifact from a previous runtime_build_and_test.yml run
      actions: read
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version-file: '.nvmrc'
          cache: yarn
          cache-dependency-path: yarn.lock
      - name: Restore cached node_modules
        uses: actions/cache@v4
        id: node_modules
        with:
          path: |
            **/node_modules
          key: runtime-release-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'scripts/release/yarn.lock') }}
      - name: Ensure clean build directory
        run: rm -rf build
      - run: yarn install --frozen-lockfile
        if: steps.node_modules.outputs.cache-hit != 'true'
      - run: yarn --cwd scripts/release install --frozen-lockfile
        if: steps.node_modules.outputs.cache-hit != 'true'
      - run: |
          GH_TOKEN=${{ secrets.GH_TOKEN }} scripts/release/prepare-release-from-ci.js --skipTests -r ${{ inputs.release_channel }} --commit=${{ inputs.commit_sha }}
          cp ./scripts/release/ci-npmrc ~/.npmrc
          scripts/release/publish.js --ci --tags ${{ inputs.dist_tag }}
      - name: Notify Discord on failure
        if: failure() && inputs.enableFailureNotification == true
        uses: tsickert/discord-webhook@86dc739f3f165f16dadc5666051c367efa1692f4
        with:
          webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
          embed-author-name: "GitHub Actions"
          embed-title: 'Publish of $${{ inputs.release_channel }} release failed'
          embed-url: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}/attempts/${{ github.run_attempt }}
