name: Update Homebrew Tap

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      tag:
        description: "Tag to update (e.g., v0.3.9)"
        required: true

permissions:
  contents: read

env:
  TAP_OWNER: theGeekist
  TAP_REPO: homebrew-skeletor
  FORMULA_PATH: Formula/skeletor.rb
  SRC_OWNER: theGeekist
  SRC_REPO: skeletor

jobs:
  tap:
    runs-on: ubuntu-latest
    steps:
      - name: Resolve release + asset urls
        id: rel
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        shell: bash
        run: |
          set -Eeuo pipefail
          TAG="${{ github.event.release.tag_name || inputs.tag || '' }}"
          [[ -n "$TAG" ]] || { echo "No tag on event"; exit 1; }

          REL_JSON="$(
            curl -fsSL -H "Authorization: Bearer ${GH_TOKEN}" \
            -H "Accept: application/vnd.github+json" \
            "https://api.github.com/repos/${SRC_OWNER}/${SRC_REPO}/releases/tags/${TAG}"
          )"

          url() { echo "$REL_JSON" | jq -r --arg n "$1" '.assets[] | select(.name==$n) | .browser_download_url'; }

          MAC_ARM_URL="$(url skeletor-macos-aarch64-apple-darwin.tar.gz)"
          MAC_X64_URL="$(url skeletor-macos-x86_64-apple-darwin.tar.gz)"
          LNX_X64_URL="$(url skeletor-ubuntu-x86_64-unknown-linux-gnu.tar.gz)"

          for u in "$MAC_ARM_URL" "$MAC_X64_URL" "$LNX_X64_URL"; do [[ -n "$u" && "$u" != "null" ]]; done

          {
            echo "tag=$TAG"
            echo "mac_arm_url=$MAC_ARM_URL"
            echo "mac_x64_url=$MAC_X64_URL"
            echo "lnx_x64_url=$LNX_X64_URL"
          } >> "$GITHUB_OUTPUT"

      - name: Download + sha256
        id: sums
        shell: bash
        run: |
          set -Eeuo pipefail
          fetch() { curl -fsSL "$1" -o "$2"; shasum -a 256 "$2" | awk '{print $1}'; }
          echo "mac_arm=$(fetch '${{ steps.rel.outputs.mac_arm_url }}' macos-arm64.tgz)" >> "$GITHUB_OUTPUT"
          echo "mac_x64=$(fetch '${{ steps.rel.outputs.mac_x64_url }}' macos-x64.tgz)" >> "$GITHUB_OUTPUT"
          echo "lnx_x64=$(fetch '${{ steps.rel.outputs.lnx_x64_url }}' linux-x64.tgz)" >> "$GITHUB_OUTPUT"

      - name: Generate formula (temp file)
        id: formula
        shell: bash
        run: |
          set -Eeuo pipefail
          TAG='${{ steps.rel.outputs.tag }}'
          HOMEPAGE="https://github.com/${{ env.SRC_OWNER }}/${{ env.SRC_REPO }}"
          mkdir -p out/Formula
          cat > "out/${{ env.FORMULA_PATH }}" <<'RUBY'
          class Skeletor < Formula
            desc "Two-way scaffolding CLI (apply + snapshot)"
            homepage "__HOMEPAGE__"
            license "MIT"
          
            on_macos do
              on_arm do
                url "__MAC_ARM_URL__"
                sha256 "__MAC_ARM_SHA__"
              end
              on_intel do
                url "__MAC_X64_URL__"
                sha256 "__MAC_X64_SHA__"
              end
            end
          
            on_linux do
              on_intel do
                url "__LNX_X64_URL__"
                sha256 "__LNX_X64_SHA__"
              end
            end
          
            def install
              bin.install "skeletor"
            end
          
            test do
              assert_match "skeletor", shell_output("#{bin}/skeletor --help")
            end
          
            livecheck do
              url :stable
              strategy :github_latest
            end
          end
          RUBY
          python - <<'PY'
          from pathlib import Path
          import os

          path = Path("out/${{ env.FORMULA_PATH }}")
          text = path.read_text()
          replacements = {
              "__HOMEPAGE__": os.environ["HOMEPAGE"],
              "__MAC_ARM_URL__": os.environ["MAC_ARM_URL"],
              "__MAC_ARM_SHA__": os.environ["MAC_ARM_SHA"],
              "__MAC_X64_URL__": os.environ["MAC_X64_URL"],
              "__MAC_X64_SHA__": os.environ["MAC_X64_SHA"],
              "__LNX_X64_URL__": os.environ["LNX_X64_URL"],
              "__LNX_X64_SHA__": os.environ["LNX_X64_SHA"],
          }
          for key, value in replacements.items():
              text = text.replace(key, value)
          path.write_text(text)
          PY
          echo "branch=tap/update-${TAG}" >> "$GITHUB_OUTPUT"
        env:
          HOMEPAGE: https://github.com/${{ env.SRC_OWNER }}/${{ env.SRC_REPO }}
          MAC_ARM_URL: ${{ steps.rel.outputs.mac_arm_url }}
          MAC_ARM_SHA: ${{ steps.sums.outputs.mac_arm }}
          MAC_X64_URL: ${{ steps.rel.outputs.mac_x64_url }}
          MAC_X64_SHA: ${{ steps.sums.outputs.mac_x64 }}
          LNX_X64_URL: ${{ steps.rel.outputs.lnx_x64_url }}
          LNX_X64_SHA: ${{ steps.sums.outputs.lnx_x64 }}

      - name: Push PR to tap
        env:
          GH_TOKEN: ${{ secrets.GH_PAT }}
        shell: bash
        run: |
          set -Eeuo pipefail
          [[ -n "${GH_TOKEN:-}" ]] || { echo "GH_PAT is missing"; exit 1; }
          BRANCH='${{ steps.formula.outputs.branch }}'
          git clone "https://github.com/${{ env.TAP_OWNER }}/${{ env.TAP_REPO }}.git" tap
          cd tap
          git checkout -b "$BRANCH"
          mkdir -p "$(dirname '${{ env.FORMULA_PATH }}')"
          cp "../out/${{ env.FORMULA_PATH }}" "${{ env.FORMULA_PATH }}"
          git add "${{ env.FORMULA_PATH }}"
          if git diff --cached --quiet; then
            echo "No changes."
            exit 0
          fi
          git -c user.name="skeletor-bot" -c user.email="skeletor-bot@users.noreply.github.com" commit -m "skeletor: update to ${{ steps.rel.outputs.tag }}"
          git push "https://${GH_TOKEN}@github.com/${{ env.TAP_OWNER }}/${{ env.TAP_REPO }}.git" "$BRANCH"
          gh pr create --repo "${{ env.TAP_OWNER }}/${{ env.TAP_REPO }}" --base main --head "$BRANCH" --title "skeletor: ${{ steps.rel.outputs.tag }}" --body "Automated update."
