name: "Publish to Extension Store"
on:
  push:
    branches:
      - main

jobs:
  check-release-requirement:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - uses: actions/setup-node@v3
        with:
          node-version: '18'
          check-latest: true

      - name: Cache npm dependencies
        uses: actions/cache@v3
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

      - name: Install dependencies
        run: npm ci

      - name: Check if release is required
        run: ls .changeset/*.md > /dev/null 2>&1 && echo "result=release-required" >> $GITHUB_OUTPUT || echo "result=no-release-required" >> $GITHUB_OUTPUT
        id: check_release
        continue-on-error: true

    outputs:
      release: ${{ steps.check_release.outputs.result }}

  build-and-publish:
    needs: check-release-requirement
    if: needs.check-release-requirement.outputs.release == 'release-required'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - uses: actions/setup-node@v3
        with:
          node-version: '18'
          check-latest: true

      - name: Cache npm dependencies
        uses: actions/cache@v3
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

      - name: Install dependencies
        run: npm ci

      - name: Update version
        run: npx changeset version

      - name: Tag version
        run: npx changeset tag

      - name: Build the extension
        run: npm run build && npm run build:firefox

      # patch for plasmo bug
      - name: remove unused permissions
        run: npm run remove-permissions

      - name: Package the extension into a zip artifact
        run: npm run package && npm run package:firefox

      - name: Publish to Extension Store
        uses: PlasmoHQ/bpp@v3
        with:
          keys: ${{ secrets.PUBLISH_KEYS }}
          artifact: build/chrome-mv3-prod.zip

      - name: Commit & Push changes
        uses: actions-js/push@master
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          message: "🔖 bump version"
          tags: true
