# Inspired by .github\workflows\publish-matterbridge-plugin-dev-daily-from-main.yml
name: Publish to npm from main branch to dev tag

on:
  # Allow manual dispatch
  workflow_dispatch:
#  push:
#    branches: [ main ]
#  # Daily at midnight UTC
#  schedule:
#    - cron: '0 0 * * *'

jobs:
  publish-dev:
    runs-on: ubuntu-latest
    steps:
      # Always check out the main branch, even for scheduled runs
      - name: Checkout main
        uses: actions/checkout@v4
        with:
          ref: main
          fetch-depth: 0

      - name: Set up Node.js & registry
        uses: actions/setup-node@v4
        with:
          node-version: '22.x'
          registry-url: 'https://registry.npmjs.org'

      - name: Clean npm cache
        run: npm cache clean --force

      - name: Lint & test & build
        run: |
          npm ci
          npm run lint
          npm t
          npm pkg delete devDependencies
          npx shx rm -rf ./node_modules
          npm install --omit=dev
          npm shrinkwrap

      - name: Extract base version and date
        id: vars
        run: |
          BASE=$(jq -r '.version' package.json)
          DATE=$(date -u +'%Y%m%d')
          SHA=$(git rev-parse --short=7 HEAD)
          DEV_TAG="${BASE}-dev-${DATE}-${SHA}"
          echo "DEV_TAG=$DEV_TAG" >> $GITHUB_ENV
          echo "ORIG_SHA=$SHA"    >> $GITHUB_ENV

      - name: Bump to date-stamped dev version (no git tag)
        run: npm version "${{ env.DEV_TAG }}" --no-git-tag-version

      - name: Check if a new dev-publish is needed
        id: check_new
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: |
          # ensure npm can read the private or public registry
          npm config set //registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN

          # 1) grab the package name
          PKG=$(node -p "require('./package.json').name")

          # 2) fetch the currently-published 'dev' dist-tag (e.g. "3.0.0-dev-20250430-1a2b3c4")
          PUBLISHED=$(npm view "$PKG" dist-tags.dev 2>/dev/null || echo "")

          # 3) extract the SHA suffix (after the last dash)
          PUBLISHED_SHA=${PUBLISHED##*-}

          # 4) get the current commit short-SHA
          CURRENT_SHA=${ORIG_SHA}

          echo "Published dev tag: $PUBLISHED"
          echo "Published SHA: $PUBLISHED_SHA"
          echo "Current SHA: $CURRENT_SHA"

          if [ "$PUBLISHED_SHA" = "$CURRENT_SHA" ]; then
            # nothing new → skip
            echo "should_publish=false" >> $GITHUB_OUTPUT
          else
            # new commit → proceed
            echo "should_publish=true"  >> $GITHUB_OUTPUT
          fi

      - name: Publish to npm under ‘dev’ tag
        if: steps.check_new.outputs.should_publish  == 'true'
        run: npm publish --tag dev
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
