name: release

# Build prebuilt binaries for macOS (arm64 + Intel) and Linux (x86_64) on
# every `v*` tag push, attach them as release assets, and publish to crates.io.
# The Homebrew formula downloads these binaries directly — end users don't
# need to compile Rust to `brew install` invoice-cli.

on:
  push:
    tags:
      - 'v*'

permissions:
  contents: write

jobs:
  build:
    name: build ${{ matrix.target }}
    runs-on: ${{ matrix.os }}
    timeout-minutes: 30
    strategy:
      fail-fast: false
      matrix:
        include:
          - target: aarch64-apple-darwin
            os: macos-15
          - target: x86_64-apple-darwin
            os: macos-15-intel
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

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

      - name: Cache cargo
        uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}

      - name: Build release
        run: cargo build --release --locked --target ${{ matrix.target }}

      - name: Package tarball
        id: package
        shell: bash
        run: |
          set -euo pipefail
          TAG="${GITHUB_REF_NAME}"
          PKG="invoice-${TAG}-${{ matrix.target }}"
          mkdir -p dist
          cp "target/${{ matrix.target }}/release/invoice" "dist/invoice"
          cp README.md LICENSE "dist/"
          cd dist
          tar czf "../${PKG}.tar.gz" invoice README.md LICENSE
          cd ..
          sha256sum "${PKG}.tar.gz" > "${PKG}.tar.gz.sha256" 2>/dev/null || shasum -a 256 "${PKG}.tar.gz" > "${PKG}.tar.gz.sha256"
          echo "pkg=${PKG}" >> "$GITHUB_OUTPUT"

      - name: Upload to release
        uses: softprops/action-gh-release@v2
        with:
          files: |
            ${{ steps.package.outputs.pkg }}.tar.gz
            ${{ steps.package.outputs.pkg }}.tar.gz.sha256

  crates-io:
    name: publish crates.io
    runs-on: ubuntu-latest
    timeout-minutes: 15
    needs: build
    if: ${{ !contains(github.ref_name, '-') }}
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@stable
      - name: Publish
        run: cargo publish --locked --token ${{ secrets.CRATES_IO_TOKEN }}
