name: Auto Publish

on:
  push:
    tags:
      - "v*"

  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: CheckOut Code
        uses: actions/checkout@master
        with:
          ref: ${{ github.ref_name }}

      - name: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          version: 9

      - name: Setup Node
        uses: actions/setup-node@v3
        with:
          node-version: 20.10.0
          registry-url: "https://registry.npmjs.org"

      - name: Get pnpm store directory
        id: pnpm-cache
        run: |
          echo "pnpm_cache_dir=$(pnpm store path)" >> $GITHUB_OUTPUT

      - uses: actions/cache@v3
        name: Setup pnpm cache
        with:
          path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}
          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-store-
      - name: Install dependencies
        run: pnpm i --no-frozen-lockfile
      - name: Build
        run: pnpm build
      - name: Clean node_modules
        run: |
          # 删除任何意外混进去的 node_modules
          ls
          rm -rf node_modules
          find template -type d -name node_modules -prune -exec rm -rf {} +
          # 生成待发布 tarball(验证用)
          npm pack --dry-run
      - name: Parse Publish tag
        id: parse_tag
        run: |
          tag_name="${GITHUB_REF#refs/tags/}"
          if [[ "$tag_name" == *alpha* ]]; then
            echo "dist_tag=alpha" >> "$GITHUB_OUTPUT"
          elif [[ "$tag_name" == *beta* ]]; then
            echo "dist_tag=beta" >> "$GITHUB_OUTPUT"
          elif [[ "$tag_name" == *rc* ]]; then
            echo "dist_tag=rc" >> "$GITHUB_OUTPUT"
          else
            echo "dist_tag=latest" >> "$GITHUB_OUTPUT"
          fi
      - name: Show version and tag
        run: |
          VERSION="$(node -p "require('./package.json').version")"
          echo "publish version: $VERSION"
          echo "publish tag: ${{ steps.parse_tag.outputs.dist_tag }}"
      - name: Publish @opentiny/tiny-toolkit-pro
        run: |
          echo "//registry.npmjs.org/:_authToken=${NODE_AUTH_TOKEN}" > ~/.npmrc
          npm publish --tag ${{ steps.parse_tag.outputs.dist_tag }}
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Release
        if: ${{ steps.parse_tag.outputs.dist_tag == 'latest' }}
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ github.ref_name }}
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}