name: Publish
on:
  workflow_dispatch:
  workflow_run:
    workflows: ["Check and Test"]
    branches: [main]
    types:
      - completed

jobs:
  publish:
    if: |
      github.event_name == 'workflow_dispatch' || (
        startsWith(github.event.workflow_run.head_commit.message, 'chore(ci): bump packages') &&
        github.event.workflow_run.conclusion == 'success'
      )

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
      with:
        # don't checkout a detatched HEAD
        ref: ${{ github.head_ref }}

        # this is important so git log has the whole history
        fetch-depth: '0'

    - name: Setup git
      run: |
        git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
        git config --local user.name "github-actions[bot]"

    - name: Setup Node.js
      uses: actions/setup-node@v3
      with:
        node-version: 18.x
        cache: 'npm'

    - name: Install npm
      run: npm install -g npm@8

    - name: Install Dependencies
      run: |
        npm ci
        npm run bootstrap-ci
      shell: bash

    - name: "Publish what is not already in NPM"
      env:
        NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
      run: |
        echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc
        git update-index --assume-unchanged .npmrc
        npm run publish-packages

    - name: "Publish tags"
      run: |
        npx lerna list -a --json | \
          jq -r '.[] | .name + "@" + .version' | \
          xargs -i sh -c "git tag -a {} -m {} || true"
        git push --follow-tags

