# Version tags only

name: Publish

on:
  push:
    tags:
      - v[0-9]+.[0-9]+.[0-9]+

jobs:
  npmPublish:
    name: Publish to npm
    runs-on: ubuntu-latest
    env:
      # It'll work with secrets.GITHUB_TOKEN (which is provided by GitHub unconditionally)
      # Still then release author would be "github-actions". It's better if it's dedicated repo bot
      GITHUB_TOKEN: ${{ secrets.USER_GITHUB_TOKEN }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v2

      - name: Retrieve dependencies from cache
        uses: actions/cache@v2
        with:
          path: |
            ~/.npm
            node_modules
            sdk-js/node_modules
          key: npm-v14-${{ runner.os }}-refs/heads/main-${{ hashFiles('**package*.json') }}

      - name: Install Node.js and npm
        uses: actions/setup-node@v1
        with:
          node-version: 14.x
          registry-url: https://registry.npmjs.org

      # Note: No need to install dependencies as we have retrieved cached `node_modules` for very
      #       same `package.json` as stored with recent `main` build

      - name: Build SDK
        run: |
          cd sdk-js
          npm run build

      - name: Publish new version
        # Note: Setting NODE_AUTH_TOKEN as job|workspace wide env var won't work
        #       as it appears actions/setup-node sets own value
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: |
          npm publish

      - name: Publish release notes
        run: |
          TEMP_ARRAY=($(echo $GITHUB_REF | tr "/" "\n"))
          TAG=${TEMP_ARRAY[@]: -1}
          npx github-release-from-cc-changelog $TAG
