name: Release

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

env:
  CARGO_TERM_COLOR: always

permissions:
  contents: write

jobs:
  build:
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            archive_ext: tar.gz
          - os: macos-15-intel
            target: x86_64-apple-darwin
            archive_ext: tar.gz
          - os: macos-14
            target: aarch64-apple-darwin
            archive_ext: tar.gz
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            archive_ext: zip

    runs-on: ${{ matrix.os }}

    steps:
      - uses: actions/checkout@v5

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

      - uses: Swatinem/rust-cache@v2

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

      - name: Package archive (Unix)
        if: runner.os != 'Windows'
        shell: bash
        run: |
          VERSION="${GITHUB_REF_NAME:-dev}"
          PKG_DIR="sxmc-${VERSION}-${{ matrix.target }}"
          mkdir -p "$PKG_DIR"
          cp "target/${{ matrix.target }}/release/sxmc" "$PKG_DIR/"
          cp README.md LICENSE "$PKG_DIR/"
          cp docs/CLIENTS.md docs/RELEASING.md docs/DISTRIBUTION.md docs/SMOKE_TESTS.md "$PKG_DIR/"
          tar -czf "${PKG_DIR}.tar.gz" "$PKG_DIR"
          shasum -a 256 "${PKG_DIR}.tar.gz" > "${PKG_DIR}.tar.gz.sha256"

      - name: Package archive (Windows)
        if: runner.os == 'Windows'
        shell: pwsh
        run: |
          $version = if ($env:GITHUB_REF_NAME) { $env:GITHUB_REF_NAME } else { "dev" }
          $pkgDir = "sxmc-$version-${{ matrix.target }}"
          New-Item -ItemType Directory -Path $pkgDir | Out-Null
          Copy-Item "target/${{ matrix.target }}/release/sxmc.exe" "$pkgDir/"
          Copy-Item README.md, LICENSE "$pkgDir/"
          Copy-Item docs/CLIENTS.md, docs/RELEASING.md, docs/DISTRIBUTION.md, docs/SMOKE_TESTS.md "$pkgDir/"
          Compress-Archive -Path $pkgDir -DestinationPath "$pkgDir.zip"
          (Get-FileHash "$pkgDir.zip" -Algorithm SHA256).Hash.ToLower() | Out-File -Encoding ascii "$pkgDir.zip.sha256"

      - name: Upload release asset
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v2
        with:
          files: |
            sxmc-${{ github.ref_name }}-${{ matrix.target }}.${{ matrix.archive_ext }}
            sxmc-${{ github.ref_name }}-${{ matrix.target }}.${{ matrix.archive_ext }}.sha256
