name: Build ehpeek

on:
  push:
  pull_request:
  workflow_dispatch:

permissions:
  contents: write

concurrency:
  group: build-ehpeek-${{ github.ref_name }}
  cancel-in-progress: false

jobs:
  build:
    name: Build ehpeek
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: "22"

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

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Type check
        run: pnpm check

      - name: Build
        env:
          EHPEEK_RELEASE_BUILD: "true"
          EHPEEK_RELEASE_BRANCH: ${{ github.ref_name }}
        run: pnpm build

      - name: Publish built userscript branch
        id: publish
        if: >-
          github.event_name != 'pull_request' &&
          (github.ref_name == 'master' || github.ref_name == 'stable')
        working-directory: .
        run: |
          safe_ref="${GITHUB_REF_NAME//\//-}"
          publish_branch="build-${safe_ref}"
          worktree="$(mktemp -d)"
          artifact="$(mktemp)"

          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"

          cp dist/ehpeek.user.js "$artifact"

          if git ls-remote --exit-code --heads origin "$publish_branch" >/dev/null 2>&1; then
            git fetch origin "$publish_branch"
            git worktree add -B "$publish_branch" "$worktree" "origin/$publish_branch"
          else
            git worktree add --detach "$worktree"
            cd "$worktree"
            git checkout --orphan "$publish_branch"
            git rm -rf . >/dev/null 2>&1 || true
            cd -
          fi

          cd "$worktree"
          cp "$artifact" ehpeek.user.js
          git add ehpeek.user.js
          if git diff --cached --quiet; then
            echo "No build output changes."
            echo "changed=false" >> "$GITHUB_OUTPUT"
            exit 0
          fi
          git commit -m "build ehpeek from ${GITHUB_SHA}"
          git push origin "HEAD:${publish_branch}"
          echo "changed=true" >> "$GITHUB_OUTPUT"

      - name: Purge jsDelivr cache
        if: steps.publish.outputs.changed == 'true'
        continue-on-error: true
        run: >-
          curl
          --fail-with-body
          --retry 3
          --retry-all-errors
          --show-error
          --silent
          "https://purge.jsdelivr.net/gh/${GITHUB_REPOSITORY}@build-${GITHUB_REF_NAME}/ehpeek.user.js"
