name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write

jobs:
  build:
    name: Build ${{ matrix.target }}
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
            archive: tar.gz
          - target: aarch64-unknown-linux-gnu
            os: ubuntu-latest
            archive: tar.gz
          - target: x86_64-apple-darwin
            os: macos-latest
            archive: tar.gz
          - target: aarch64-apple-darwin
            os: macos-latest
            archive: tar.gz
          - target: x86_64-pc-windows-msvc
            os: windows-latest
            archive: zip

    steps:
      - uses: actions/checkout@v4

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

      - name: Install cross-compilation tools (Linux aarch64)
        if: matrix.target == 'aarch64-unknown-linux-gnu'
        run: |
          sudo apt-get update
          sudo apt-get install -y gcc-aarch64-linux-gnu

      - name: Configure cross-compilation (Linux aarch64)
        if: matrix.target == 'aarch64-unknown-linux-gnu'
        run: |
          echo '[target.aarch64-unknown-linux-gnu]' >> ~/.cargo/config.toml
          echo 'linker = "aarch64-linux-gnu-gcc"' >> ~/.cargo/config.toml

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

      - name: Package (Unix)
        if: matrix.archive == 'tar.gz'
        shell: bash
        run: |
          BINARY=target/${{ matrix.target }}/release/sipp
          ARCHIVE=sipp-${{ github.ref_name }}-${{ matrix.target }}.tar.gz
          tar -czf "$ARCHIVE" -C "$(dirname $BINARY)" "$(basename $BINARY)"
          echo "ASSET=$ARCHIVE" >> $GITHUB_ENV

      - name: Package (Windows)
        if: matrix.archive == 'zip'
        shell: pwsh
        run: |
          $binary = "target\${{ matrix.target }}\release\sipp.exe"
          $archive = "sipp-${{ github.ref_name }}-${{ matrix.target }}.zip"
          Compress-Archive -Path $binary -DestinationPath $archive
          echo "ASSET=$archive" | Out-File -FilePath $env:GITHUB_ENV -Append

      - name: Upload to release
        uses: softprops/action-gh-release@v2
        with:
          files: ${{ env.ASSET }}
