name: Build

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: docker
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
        with:
          ref: ${{ github.head_ref }}
          fetch-depth: 0

      - uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4
        with:
          run_install: |
            - recursive: true
              args: [--frozen-lockfile, --strict-peer-dependencies]

      - name: Build
        run: |
          pnpm build --dest DIST
          rm -rf .pnpm-store

      - name: Commit build
        run: |
          current_version=v$(cat package.json | grep version | grep -o -E '([0-9]+\.){2}[0-9]+')

          git switch build
          previous_version=$(git describe --tags --abbrev=0 2>/dev/null || echo '')
          tag_message=`git log --pretty='format:%s' $previous_version..`

          shopt -s extglob
          shopt -s dotglob
          rm -rf !(DIST|.git|.|..)
          mv DIST/* .
          rm -rf DIST

          git add -A
          git config --local user.email "forgejo-actions[bot]@noreply.pleshevski.ru"
          git config --local user.name "Forgejo actions[bot]"
          git commit -m "Deploy $(date +%Y-%m-%d)" --allow-empty

          if [[ "$current_version" != "$previous_version" ]]; then
            git tag $current_version -m "$current_version

            $tag_message"
          fi

      - name: Push changes
        uses: ad-m/github-push-action@d91a481090679876dfc4178fef17f286781251df # v0.8.0
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          branch: build
          tags: true