name: Release

on:
  push:
    tags:
      - 'v[0-9]+.[0-9]+.[0-9]+*'
  workflow_dispatch:

permissions:
  contents: write

jobs:
  create-release:
    name: Create Release
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
      - name: Create GitHub Release
        uses: taiki-e/create-gh-release-action@eba8ea96c86cca8a37f1b56e94b4d13301fba651 # v1.11.0
        with:
          token: ${{ secrets.GITHUB_TOKEN }}

  build-release:
    name: Release (${{ matrix.target }})
    needs: create-release
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - target: x86_64-unknown-linux-musl
            os: ubuntu-latest
            asset_name: pinner-linux-amd64
          - target: aarch64-unknown-linux-musl
            os: ubuntu-latest
            asset_name: pinner-linux-arm64
          - target: x86_64-apple-darwin
            os: macos-latest
            asset_name: pinner-macos-amd64
          - target: aarch64-apple-darwin
            os: macos-latest
            asset_name: pinner-macos-arm64
          - target: x86_64-pc-windows-msvc
            os: windows-latest
            asset_name: pinner-windows-amd64
          - target: aarch64-pc-windows-msvc
            os: windows-latest
            asset_name: pinner-windows-arm64

    steps:
      - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
      
      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 # v1
        with:
          toolchain: stable
          targets: ${{ matrix.target }}

      - name: Build and upload binaries
        uses: taiki-e/upload-rust-binary-action@f0d45ae91ee7b8ee928de7a9d04d893a08bcbec6 # v1.30.2
        with:
          bin: pinner
          target: ${{ matrix.target }}
          archive: ${{ matrix.asset_name }}
          token: ${{ secrets.GITHUB_TOKEN }}

  publish-crates-io:
    name: Publish to crates.io
    needs: build-release
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v')
    steps:
      - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 # v1
        with:
          toolchain: stable
      - name: Publish
        run: cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
