name: Homebrew Formula update

# Re-pin Formula/phostt.rb to the freshly-published release tarballs
# every time the `Release` workflow finishes successfully on a `v*` tag.
# Reads the SHA256SUMS.txt asset from the GitHub release and rewrites the
# `sha256` lines in-place, then commits back to `main`.

on:
  workflow_run:
    workflows: [Release]
    types: [completed]
  workflow_dispatch:
    inputs:
      tag:
        description: 'Release tag to pin Formula against (e.g. v0.9.3)'
        required: true

permissions:
  contents: write

jobs:
  update-formula:
    if: >-
      github.event_name == 'workflow_dispatch' ||
      (github.event.workflow_run.conclusion == 'success' &&
       startsWith(github.event.workflow_run.head_branch, 'v'))
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          ref: main
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Resolve tag
        id: tag
        shell: bash
        run: |
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            echo "tag=${{ inputs.tag }}" >> "$GITHUB_OUTPUT"
          else
            echo "tag=${{ github.event.workflow_run.head_branch }}" >> "$GITHUB_OUTPUT"
          fi

      - name: Fetch SHA256SUMS
        id: shas
        shell: bash
        env:
          TAG: ${{ steps.tag.outputs.tag }}
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          set -euo pipefail
          VERSION="${TAG#v}"
          gh release download "$TAG" --pattern 'SHA256SUMS.txt' --dir . --clobber
          MAC_ARM=$(awk -v a="phostt-${VERSION}-aarch64-apple-darwin.tar.gz"    '$2==a{print $1}' SHA256SUMS.txt)
          LIN_X86=$(awk -v a="phostt-${VERSION}-x86_64-unknown-linux-gnu.tar.gz" '$2==a{print $1}' SHA256SUMS.txt)
          if [ -z "$MAC_ARM" ] || [ -z "$LIN_X86" ]; then
            echo "::error ::SHA256SUMS.txt is missing one of the expected assets" >&2
            cat SHA256SUMS.txt >&2
            exit 1
          fi
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"
          echo "mac_arm=$MAC_ARM" >> "$GITHUB_OUTPUT"
          echo "linux_x86=$LIN_X86" >> "$GITHUB_OUTPUT"

      - name: Rewrite Formula/phostt.rb
        shell: bash
        env:
          VERSION: ${{ steps.shas.outputs.version }}
          MAC_ARM: ${{ steps.shas.outputs.mac_arm }}
          LINUX_X86: ${{ steps.shas.outputs.linux_x86 }}
        run: |
          set -euo pipefail
          python3 - <<'PY'
          import os, re, pathlib
          version = os.environ['VERSION']
          mac = os.environ['MAC_ARM']
          lin = os.environ['LINUX_X86']
          p = pathlib.Path('Formula/phostt.rb')
          text = p.read_text()
          text = re.sub(r'version "[^"]+"', f'version "{version}"', text, count=1)
          text = re.sub(
              r'(aarch64-apple-darwin\.tar\.gz"\s+sha256 ")[0-9a-f]{64}(")',
              lambda m: m.group(1) + mac + m.group(2),
              text, count=1, flags=re.S,
          )
          text = re.sub(
              r'(x86_64-unknown-linux-gnu\.tar\.gz"\s+sha256 ")[0-9a-f]{64}(")',
              lambda m: m.group(1) + lin + m.group(2),
              text, count=1, flags=re.S,
          )
          text = re.sub(
              r'releases/download/v[0-9][0-9a-zA-Z.\-+]*/phostt-[0-9][0-9a-zA-Z.\-+]*-aarch64-apple-darwin\.tar\.gz',
              f'releases/download/v{version}/phostt-{version}-aarch64-apple-darwin.tar.gz',
              text, count=1,
          )
          text = re.sub(
              r'releases/download/v[0-9][0-9a-zA-Z.\-+]*/phostt-[0-9][0-9a-zA-Z.\-+]*-x86_64-unknown-linux-gnu\.tar\.gz',
              f'releases/download/v{version}/phostt-{version}-x86_64-unknown-linux-gnu.tar.gz',
              text, count=1,
          )
          p.write_text(text)
          PY
          head -n 40 Formula/phostt.rb

      - name: Commit + push
        shell: bash
        env:
          TAG: ${{ steps.tag.outputs.tag }}
        run: |
          set -euo pipefail
          if git diff --quiet Formula/phostt.rb; then
            echo "No Formula changes for $TAG — nothing to commit"
            exit 0
          fi
          git config user.name  'github-actions[bot]'
          git config user.email 'github-actions[bot]@users.noreply.github.com'
          git add Formula/phostt.rb
          git commit -m "chore(brew): pin Formula to $TAG

          Auto-generated by .github/workflows/homebrew.yml after the release
          pipeline published the ${TAG} tarballs. SHAs copied verbatim from
          the release's SHA256SUMS.txt asset."
          git push origin main
