name: Release

on:
  push:
    tags:
      - "v*.*.*"
  workflow_dispatch:
    inputs:
      tag:
        description: "Tag to release (e.g., v0.3.9)"
        required: true

permissions:
  contents: write  # create/edit GitHub Releases
  id-token: write  # (optional) for provenance/signing later

jobs:
  build-and-publish:
    strategy:
      fail-fast: false
      matrix:
        include:
          # Apple Silicon
          - os: macos-14
            target: aarch64-apple-darwin
            out: skeletor-macos-aarch64-apple-darwin
          # Intel mac
          - os: macos-14
            target: x86_64-apple-darwin
            out: skeletor-macos-x86_64-apple-darwin
          # Linux x86_64 (gnu)
          - os: ubuntu-22.04
            target: x86_64-unknown-linux-gnu
            out: skeletor-ubuntu-x86_64-unknown-linux-gnu

    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ inputs.tag || github.ref_name }}

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

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

      - name: Package tarball
        shell: bash
        run: |
          set -euo pipefail
          mkdir -p "dist/${{ matrix.out }}"
          BIN="target/${{ matrix.target }}/release/skeletor"
          cp "$BIN" "dist/${{ matrix.out }}/skeletor"
          tar -C dist -czf "${{ matrix.out }}.tar.gz" "${{ matrix.out }}"
          shasum -a 256 "${{ matrix.out }}.tar.gz" | awk '{print $1}' > "${{ matrix.out }}.sha256"

      - name: Create Release (if missing)
        id: create_release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ inputs.tag || github.ref_name }}
          draft: false
          prerelease: ${{ contains(inputs.tag || github.ref_name, '-') }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Upload assets
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ inputs.tag || github.ref_name }}
          files: |
            ${{ matrix.out }}.tar.gz
            ${{ matrix.out }}.sha256
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
