name: Release

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:

permissions:
  contents: write

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      # Tag pushes only: workflow_dispatch from a branch has no tag to release.
      - name: Create draft release
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v3
        with:
          name: Release ${{ github.ref_name }}
          tag_name: ${{ github.ref_name }}
          draft: true
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  bump-homebrew-formula:
    name: Bump Homebrew formula
    runs-on: ubuntu-latest
    # workflow_dispatch has no tag — tarball URL would be wrong.
    if: startsWith(github.ref, 'refs/tags/')
    steps:
      - name: Checkout main
        uses: actions/checkout@v6
        with:
          ref: main
          fetch-depth: 0

      - name: Update Formula/tetration.rb (url + sha256)
        env:
          TAG: ${{ github.ref_name }}
          REPO: ${{ github.repository }}
        run: python3 .github/scripts/bump-homebrew-formula.py

      # Plain `git commit` is unsigned; main requires verified signatures.
      - name: Commit and push (verified)
        uses: iarekylew00t/verified-bot-commit@v2
        with:
          ref: main
          message: "brew: bump formula to ${{ github.ref_name }}"
          files: |
            Formula/tetration.rb
          if-no-commit: info

  publish:
    name: Publish to crates.io
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/')
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v6

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: '1.95'

      - name: Install HDF5 and NetCDF (Ubuntu)
        run: |
          sudo apt-get update
          sudo apt-get install -y libhdf5-dev libnetcdf-dev pkg-config

      - uses: rust-lang/crates-io-auth-action@v1
        id: auth

      - run: cargo publish --locked
        env:
          CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
