name: release

on:
  push:
    tags:
      - '*-coa.*'   # Asc-1.1.6-coa.2, 9.1.40-coa.3, etc.
      - 'v*'        # v0.3.0 for repos without an upstream version

jobs:
  release:
    runs-on: linux-amd64
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0   # build_zip uses git archive HEAD; full history is fine

      - name: Build per-addon zip(s)
        run: bash tools/build_zip.sh

      - name: Publish release (Gitea API direct; no action dependency)
        env:
          GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          REPO: ${{ github.repository }}
          TAG:  ${{ github.ref_name }}
          API:  ${{ github.server_url }}/api/v1
          # Gitea attachment ceiling is 200 MiB (see roles/gitea config).
          # Skip anything larger so one oversized asset doesn't fail the job.
          MAX_BYTES: 209715200
        run: |
          set -euo pipefail
          # Create the release (or reuse if it already exists for this tag).
          RID=$(curl -s -H "Authorization: token $GITEA_TOKEN" \
            "$API/repos/$REPO/releases/tags/$TAG" 2>/dev/null \
            | jq -r '.id // empty')
          if [ -z "$RID" ]; then
            RID=$(curl -sf -X POST -H "Authorization: token $GITEA_TOKEN" \
              -H "Content-Type: application/json" \
              "$API/repos/$REPO/releases" \
              -d "$(jq -nc --arg t "$TAG" '{tag_name:$t,name:$t,draft:false,prerelease:false}')" \
              | jq -r '.id')
          fi
          echo "release id: $RID"
          # Upload every dist/*.zip. Per-asset failures don't fail the job —
          # we want partial releases to still publish rather than block the
          # whole pipeline on one big file.
          failed=0
          uploaded=0
          for f in dist/*.zip; do
            name=$(basename "$f")
            size=$(stat -c '%s' "$f")
            if [ "$size" -gt "$MAX_BYTES" ]; then
              echo "::warning::skip $name (${size} B > ${MAX_BYTES} B Gitea limit; host on CDN instead)"
              failed=$((failed+1))
              continue
            fi
            echo "uploading $name ($(numfmt --to=iec "$size"))"
            if curl -sf -X POST -H "Authorization: token $GITEA_TOKEN" \
                -F "attachment=@$f" \
                "$API/repos/$REPO/releases/$RID/assets?name=$name" \
                | jq -r '"  -> " + .browser_download_url'; then
              uploaded=$((uploaded+1))
            else
              echo "::warning::upload failed for $name"
              failed=$((failed+1))
            fi
          done
          echo "release published: $uploaded uploaded, $failed skipped/failed"
          # Only fail the job if NO assets uploaded — a release with zero
          # attachments isn't useful to anyone.
          [ "$uploaded" -gt 0 ]
