name: Release

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

permissions:
  contents: write

env:
  BIN_NAME: ilmari

jobs:
  build:
    name: Build ${{ matrix.target }}
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-musl
            use_cross: true
          - os: ubuntu-latest
            target: aarch64-unknown-linux-musl
            use_cross: true
          - os: macos-15-intel
            target: x86_64-apple-darwin
            use_cross: false
          - os: macos-15
            target: aarch64-apple-darwin
            use_cross: false
          - os: windows-2022
            target: x86_64-pc-windows-msvc
            use_cross: false

    steps:
      - uses: actions/checkout@v5

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}
      - name: Restore Rust cache
        uses: Swatinem/rust-cache@v2
        with:
          shared-key: release-${{ runner.os }}-${{ matrix.target }}
          save-if: ${{ github.event_name != 'pull_request' }}
          cache-on-failure: true

      - name: Setup cross
        if: matrix.use_cross
        uses: taiki-e/setup-cross-toolchain-action@v1
        with:
          target: ${{ matrix.target }}

      - name: Resolve version
        id: version
        shell: bash
        run: scripts/resolve-version.sh

      - name: Build (unix)
        if: runner.os != 'Windows'
        run: TARGET=${{ matrix.target }} scripts/build-release.sh

      - name: Build (windows)
        if: runner.os == 'Windows'
        shell: pwsh
        run: scripts/build-release.ps1 -Target ${{ matrix.target }}

      - name: Package (unix)
        if: runner.os != 'Windows'
        run: TARGET=${{ matrix.target }} VERSION=${{ steps.version.outputs.version }} BIN_NAME=${{ env.BIN_NAME }} scripts/package-release.sh

      - name: Package (windows)
        if: runner.os == 'Windows'
        shell: pwsh
        run: scripts/package-release.ps1 -Target ${{ matrix.target }} -Version ${{ steps.version.outputs.version }} -BinName ${{ env.BIN_NAME }}

      - name: Upload workflow artifacts
        uses: actions/upload-artifact@v4
        with:
          name: dist-${{ matrix.target }}
          path: dist/*

      - name: Upload GitHub Release assets
        uses: softprops/action-gh-release@v2
        with:
          files: dist/*
