# Builds Ziggity for every supported OS/arch and publishes a GitHub Release
# with the binaries attached. Thanks to Zig's cross-compilation, one Linux
# runner produces all of them.
name: release

# ── When does this run? ───────────────────────────────────────────────────
on:
  push:
    tags:
      - "v*"            # e.g. pushing the tag `v0.1.0` triggers a release
  workflow_dispatch: {} # ...and you can also start it by hand from the Actions tab

# The default token is read-only; creating a Release needs write access to the repo.
permissions:
  contents: write

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      # 1. Get the source (this exact tag's code).
      - uses: actions/checkout@v5

      # 2. Install the pinned Zig version. Zig is pre-1.0 and breaks between
      #    versions, so we lock it to what the project builds with.
      #    (Still on Node 20 as of v2.2.1 — GitHub runs it on Node 24 anyway;
      #    bump the major once mlugg/setup-zig ships a Node 24 release.)
      - uses: mlugg/setup-zig@v2
        with:
          version: 0.16.0

      # 3. Gate the release on the test suite — never ship a broken build.
      - name: Test
        run: zig build test

      # 4. Cross-compile every target and package each binary.
      - name: Build & package all targets
        run: |
          set -euo pipefail
          version="${GITHUB_REF_NAME}"   # the tag name, e.g. v0.1.0
          mkdir -p dist

          # <arch>-<os>-<abi>. musl → fully static Linux binaries that run on
          # any distro; windows-gnu → self-contained (no MSVC needed);
          # linux-android → static aarch64 binary for Termux on Android (no libc,
          # so it needs no NDK). See the README "Android (Termux)" section.
          # NOTE: the Windows build compiles and libvaxis supports Windows, but
          # it hasn't been smoke-tested on a real Windows box yet. The Android
          # binary has been verified in Termux on an emulator.
          targets=(
            aarch64-macos
            x86_64-macos
            x86_64-linux-musl
            aarch64-linux-musl
            riscv64-linux-musl
            aarch64-linux-android
            x86_64-windows-gnu
          )

          for t in "${targets[@]}"; do
            echo "::group::$t"
            # ReleaseSafe: optimized, but keeps runtime safety checks (good for
            # a tool that shells out to git and touches your repo).
            zig build -Dtarget="$t" -Doptimize=ReleaseSafe --prefix "zig-out/$t"

            bindir="zig-out/$t/bin"
            name="ziggity-${version}-${t}"
            if [[ "$t" == *windows* ]]; then
              (cd "$bindir" && zip -q "${GITHUB_WORKSPACE}/dist/${name}.zip" ziggity.exe)
            else
              tar -czf "dist/${name}.tar.gz" -C "$bindir" ziggity
            fi
            echo "::endgroup::"
          done

          # Checksums so users (and package managers) can verify downloads.
          (cd dist && sha256sum * > checksums.txt)
          ls -la dist

      # 5. Create/update the GitHub Release for this tag and upload everything.
      #    Only on a tag push — a manual (workflow_dispatch) run stops after the
      #    build/package steps above, letting you dry-run without a release.
      - name: Publish release
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v3
        with:
          files: dist/*
          generate_release_notes: true   # auto-summarise commits since the last tag

      # 6. Point the Homebrew tap at this release: render Formula/ziggity.rb from
      #    the template (new version + URLs + sha256s) and push it to
      #    simoarpe/homebrew-ziggity. Needs a token that can write to THAT repo —
      #    the default GITHUB_TOKEN only covers this one. Create a fine-grained
      #    PAT (contents: write on the tap repo) and add it as the repo secret
      #    Z_HOMEBREW_TAP_TOKEN. Without it, this step logs and skips (releases still
      #    succeed).
      - name: Update Homebrew tap
        if: startsWith(github.ref, 'refs/tags/')
        env:
          TAP_TOKEN: ${{ secrets.Z_HOMEBREW_TAP_TOKEN }}
        run: |
          set -euo pipefail
          if [ -z "${TAP_TOKEN}" ]; then
            echo "Z_HOMEBREW_TAP_TOKEN not set — skipping the formula bump."
            exit 0
          fi

          tag="${GITHUB_REF_NAME}"          # v0.2.0
          version="${tag#v}"                # 0.2.0
          base="https://github.com/${GITHUB_REPOSITORY}/releases/download/${tag}"

          # sha256 of a given asset, from the checksums we just generated.
          sha() { awk -v f="ziggity-${tag}-$1" '$2==f{print $1}' dist/checksums.txt; }

          sed \
            -e "s|__VERSION__|${version}|g" \
            -e "s|__TAG__|${tag}|g" \
            -e "s|__BASE__|${base}|g" \
            -e "s|__SHA_MAC_ARM__|$(sha aarch64-macos.tar.gz)|g" \
            -e "s|__SHA_MAC_X64__|$(sha x86_64-macos.tar.gz)|g" \
            -e "s|__SHA_LIN_ARM__|$(sha aarch64-linux-musl.tar.gz)|g" \
            -e "s|__SHA_LIN_X64__|$(sha x86_64-linux-musl.tar.gz)|g" \
            .github/homebrew/ziggity.rb.tmpl > /tmp/ziggity.rb

          git clone --depth 1 \
            "https://x-access-token:${TAP_TOKEN}@github.com/simoarpe/homebrew-ziggity.git" tap
          mkdir -p tap/Formula
          cp /tmp/ziggity.rb tap/Formula/ziggity.rb
          cd tap
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          if git diff --quiet; then
            echo "Formula already up to date."
          else
            git add Formula/ziggity.rb
            git commit -m "ziggity ${version}"
            git push
          fi
