name: Publish Package to npmjs
on:
  push:
    branches:
      - alpha
      - next
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      # Setup .npmrc file to publish to npm
      - uses: actions/setup-node@v3
        with:
          node-version: '18.x'
          registry-url: 'https://registry.npmjs.org'

      # waiting https://github.com/ds300/patch-package/issues/339
      - run: npm install 2>&1 || true && npm run test:init 2>&1 || true && npm run test
      
      # resolve version
      - run: |
          set -x
          BRANCH=${GITHUB_REF##*/}
          PACKAGE=$(cat package.json | jq -r '.["name"]')
          VERLOC=$(cat package.json | jq -r '.["version"]')
          VERNPMRAW=$(curl -s https://registry.npmjs.org/$PACKAGE | jq -r '.["dist-tags"].'$BRANCH'')
          BUILD_VERSION=1
          if [[ "$VERNPMRAW" == "null" ]]; then
              VEROUT=$VERLOC
          else
              VERNPM=$(echo $VERNPMRAW | cut -d'-' -f1)
              if [[ "$VERLOC" == "$VERNPM" ]]; then
                  BUILD_VERSION=$(echo $VERNPMRAW | awk -F '[.-]' '{print $5+1}')
              fi
              VEROUT=$VERLOC
          fi
          jq -r '.version = "'${VEROUT}'-build.'$BUILD_VERSION'"' package.json > /tmp/package.json && mv /tmp/package.json ./package.json
      - run: npm publish --tag ${GITHUB_REF##*/}
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
