name: Release
run-name: ${{ github.ref_name }} Release

on:
  push:
    branches: 
      - main
      - alpha

jobs:
  call-test-workflow:
    uses: ./.github/workflows/test-flow.yaml
    with:
      from: ${{ github.workflow }}
  release:
    runs-on: ubuntu-latest
    needs: call-test-workflow

    steps:
      # Use our auto-commit permissioned app for our git actions
      - uses: actions/create-github-app-token@v1
        id: app-token
        with:
          app-id: ${{ secrets.AUTO_COMMIT_APP_ID }}
          private-key: ${{ secrets.AUTO_COMMIT_APP_PKEY }}
      - uses: actions/checkout@v4
        with:
          token: ${{ steps.app-token.outputs.token }}
      - name: Use Node.js 20.x
        uses: actions/setup-node@v3
        with:
          node-version: 20.x
      - name: Enable yarn Berry
        run: corepack enable
      - name: Install
        run: |
          yarn install --immutable
      - name: Build
        run: yarn build
      - name: Release
        shell: bash
        run: yarn release
        env:
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
          GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
      # Note - we publish doc on non-release steps as well (i.e. a docs: commit)
      # So we need the last tagged version and to make sure we are on the latest commit (to avoid re-runs on old actions)
      - name: Should Publish Doc Check
        id: publish-doc-check
        shell: bash
        run: |
          # First ensure that we are still up-to-date 
          # (do not allow reruns on old commits to override doc)
          up_to_date=$(git status | grep "branch is up to date" || echo "false")

          if [ "$up_to_date" ==  "false" ]; then
              echo "Branch is not up to date and therefore will not publish documentation!"
              exit
          fi
          # Get the last release tag on this branch (since we only publish doc with a successful publish)
          # Note - the semantic-release step will have tagged if it performed a release
          git fetch --tags
          last_version=$(git describe --tags --abbrev=0 || false)

          if [ "$last_version" == "false" ]; then
            echo "No published version detected on branch.  Skipping publishing documentation!"
            exit
          fi

          echo "version=${last_version}" >> "$GITHUB_OUTPUT"
      - name: Publish documentation
        if: ${{ steps.publish-doc-check.outputs.version }}
        run: |
          pip install -r docs/requirements.txt
          git config user.name docs-bot
          git config user.email docs-bot@hanseltime.com
          ./bin/publish-docs.sh "${{ steps.publish-doc-check.outputs.version }}"
