name: Release macOS

on:
  push:
    tags:
      - 'v*' # Triggers on tags like v0.1.0, v1.0.0

jobs:
  deploy-mac:
    strategy:
      matrix:
        include:
          - target: aarch64-apple-darwin
            runner: macos-latest
            arch: arm64
            suffix: ""
          - target: x86_64-apple-darwin
            runner: macos-latest
            arch: x86_64
            suffix: "-x86_64"
    runs-on: ${{ matrix.runner }}
    steps:
      - name: Checkout Code
        uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4

      - name: Install Rust
        uses: dtolnay/rust-toolchain@631a55b12751854ce901bb631d5902ceb48146f7 # stable
        with:
          targets: ${{ matrix.target }}

      - name: Run Tests
        run: cargo test

      - name: Build Binary (Release)
        run: cargo build --release --target ${{ matrix.target }}

      - name: Install minisign
        run: brew install minisign

      - name: Prepare Artifacts
        env:
          MINISIGN_SECRET_KEY: ${{ secrets.MINISIGN_SECRET_KEY }}
        run: |
          # Create directory structure for R2
          mkdir -p artifacts/macos/archive

          # Prepare binary
          cp target/${{ matrix.target }}/release/suv suv

          # Create main tarball (e.g. suv-macos-latest.tar.gz or suv-macos-x86_64-latest.tar.gz)
          tar -czf artifacts/macos/suv-macos${{ matrix.suffix }}-latest.tar.gz suv LICENSE scripts/uninstall.sh

          # Generate SHA256 checksums
          shasum -a 256 artifacts/macos/suv-macos${{ matrix.suffix }}-latest.tar.gz | awk '{print $1}' > artifacts/macos/suv-macos${{ matrix.suffix }}-latest.tar.gz.sha256

          # Sign with minisign (secret key from GitHub Secrets, empty password piped)
          echo "$MINISIGN_SECRET_KEY" > /tmp/minisign.key
          echo '' | minisign -S -s /tmp/minisign.key -m artifacts/macos/suv-macos${{ matrix.suffix }}-latest.tar.gz \
            -t "suvadu ${{ github.ref_name }} macOS${{ matrix.suffix }}" -x artifacts/macos/suv-macos${{ matrix.suffix }}-latest.tar.gz.minisig
          rm -f /tmp/minisign.key

          # Create versioned tarball (e.g. suv-macos-v0.1.0.tar.gz)
          cp artifacts/macos/suv-macos${{ matrix.suffix }}-latest.tar.gz artifacts/macos/archive/suv-macos${{ matrix.suffix }}-${{ github.ref_name }}.tar.gz
          cp artifacts/macos/suv-macos${{ matrix.suffix }}-latest.tar.gz.sha256 artifacts/macos/archive/suv-macos${{ matrix.suffix }}-${{ github.ref_name }}.tar.gz.sha256
          cp artifacts/macos/suv-macos${{ matrix.suffix }}-latest.tar.gz.minisig artifacts/macos/archive/suv-macos${{ matrix.suffix }}-${{ github.ref_name }}.tar.gz.minisig

      - name: Upload to Cloudflare R2
        uses: ryand56/r2-upload-action@b801a390acbdeb034c5e684ff5e1361c06639e7c # v1.4
        with:
          r2-account-id: ${{ secrets.R2_ACCOUNT_ID }}
          r2-access-key-id: ${{ secrets.R2_ACCESS_KEY_ID }}
          r2-secret-access-key: ${{ secrets.R2_SECRET_ACCESS_KEY }}
          r2-bucket: ${{ secrets.R2_BUCKET }}
          source-dir: artifacts
          destination-dir: ./ # Destination prefix in bucket

      - name: Purge Cloudflare CDN Cache
        run: |
          curl -s -X POST \
            "https://api.cloudflare.com/client/v4/zones/${{ secrets.CF_ZONE_ID }}/purge_cache" \
            -H "Authorization: Bearer ${{ secrets.CF_PURGE_TOKEN }}" \
            -H "Content-Type: application/json" \
            -d '{
              "files": [
                "https://downloads.appachi.tech/macos/suv-macos${{ matrix.suffix }}-latest.tar.gz",
                "https://downloads.appachi.tech/macos/suv-macos${{ matrix.suffix }}-latest.tar.gz.sha256",
                "https://downloads.appachi.tech/macos/suv-macos${{ matrix.suffix }}-latest.tar.gz.minisig"
              ]
            }'

      - name: Checkout Homebrew Tap
        if: matrix.suffix == ''
        uses: actions/checkout@v4
        with:
          repository: AppachiTech/homebrew-suvadu
          token: ${{ secrets.GH_PAT }}
          path: homebrew-tap

      - name: Update Homebrew Tap
        if: matrix.suffix == ''
        run: |
          TAG=${{ github.ref_name }}
          TARBALL_NAME="suv-macos-${TAG}.tar.gz"
          TARBALL_PATH="artifacts/macos/archive/${TARBALL_NAME}"

          # Calculate SHA256
          SHASUM=$(shasum -a 256 "$TARBALL_PATH" | awk '{print $1}')
          echo "SHA256: $SHASUM"

          cd homebrew-tap
          FORMULA_PATH="Formula/suvadu.rb"

          # Update version, URL, and SHA256
          sed -i '' "s/version \".*\"/version \"${TAG#v}\"/" "$FORMULA_PATH"
          NEW_URL="https://downloads.appachi.tech/macos/archive/${TARBALL_NAME}"
          sed -i '' "s|url \".*\"|url \"${NEW_URL}\"|" "$FORMULA_PATH"
          sed -i '' "s/sha256 \".*\"/sha256 \"${SHASUM}\"/" "$FORMULA_PATH"

          # Commit and push
          git config user.name "Appachi Bot"
          git config user.email "bot@appachi.tech"
          git add "$FORMULA_PATH"
          git commit -m "Update suvadu to $TAG"
          git push

      - name: Create GitHub Release
        uses: softprops/action-gh-release@a06a81a03ee405af7f2048a818ed3f03bbf83c7b # v2.5.0
        with:
          generate_release_notes: ${{ matrix.suffix == '' }}
          files: |
            artifacts/macos/archive/suv-macos${{ matrix.suffix }}-${{ github.ref_name }}.tar.gz
            artifacts/macos/archive/suv-macos${{ matrix.suffix }}-${{ github.ref_name }}.tar.gz.sha256
            artifacts/macos/archive/suv-macos${{ matrix.suffix }}-${{ github.ref_name }}.tar.gz.minisig
