name: Release

on:
  push:
    tags: ["v*"]

env:
  CARGO_TERM_COLOR: always

jobs:
  build:
    strategy:
      matrix:
        target:
          - os: ubuntu-latest
            triple: x86_64-unknown-linux-musl
          - os: ubuntu-latest
            triple: aarch64-unknown-linux-musl
          - os: macos-latest
            triple: x86_64-apple-darwin
          - os: macos-latest
            triple: aarch64-apple-darwin
          - os: windows-latest
            triple: x86_64-pc-windows-msvc
    runs-on: ${{ matrix.target.os }}
    steps:
      - uses: actions/checkout@v5

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

      - name: Install musl tools
        if: runner.os == 'Linux'
        run: sudo apt-get update && sudo apt-get install -y musl-tools

      - name: Install aarch64 musl toolchain
        if: matrix.target.triple == 'aarch64-unknown-linux-musl'
        run: |
          curl -sSL https://github.com/cross-tools/musl-cross/releases/latest/download/aarch64-unknown-linux-musl.tar.xz | tar -xJ -C /tmp
          echo "/tmp/aarch64-unknown-linux-musl/bin" >> $GITHUB_PATH

      - name: Set cross-compile env
        if: matrix.target.triple == 'aarch64-unknown-linux-musl'
        run: |
          echo "CC_aarch64_unknown_linux_musl=aarch64-unknown-linux-musl-gcc" >> $GITHUB_ENV
          echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-unknown-linux-musl-gcc" >> $GITHUB_ENV

      - uses: Swatinem/rust-cache@v2

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

      - name: Rename binary with target triple
        shell: bash
        run: |
          cd target/${{ matrix.target.triple }}/release
          for f in rssume rssume.exe rssume.d rssume.pdb; do
            [ -f "$f" ] && mv "$f" "${f/rssume/rssume-${{ matrix.target.triple }}}"
          done

      - name: Upload artifact
        uses: actions/upload-artifact@v5
        with:
          name: rssume-${{ matrix.target.triple }}
          path: target/${{ matrix.target.triple }}/release/rssume-*

  release:
    needs: build
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/download-artifact@v5
        with:
          path: artifacts

      - name: Create release
        uses: softprops/action-gh-release@v2
        with:
          name: rssume ${{ github.ref_name }}
          files: artifacts/**/*
          generate_release_notes: true
