name: App Release

on:
  release:
    types: [created]

permissions:
  contents: write
  issues: write
  pull-requests: write
  actions: write
  deployments: write
  packages: write
  repository-projects: write
  security-events: write
  statuses: write

jobs:
  build:
    name: Build and release for ${{ matrix.os }}
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [linux-latest, windows-latest, macos-latest]
        include:
          - os: linux-latest
            target: x86_64-unknown-linux-gnu
            name: Linux X64 (GNU) Release
            asset_name: raft-linux-x86_64-musl.tar.gz
            bin: raft
            asset_content_type: application/gzip
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            name: Windows X64 (MSVC) Release
            asset_name: raft-windows-x86_64-msvc.zip
            bin: raft.exe
            asset_content_type: application/zip
          - os: macos-latest
            target: x86_64-apple-darwin
            name: MacOS X64 (Darwin) Release
            asset_name: raft-macos-x86_64.tar.gz
            bin: raft
            asset_content_type: application/gzip

    steps:
    - name: Checkout
      uses: actions/checkout@v4

    - name: Setup Rust
      uses: actions-rust-lang/setup-rust-toolchain@v1
      with:
        target: ${{ matrix.target }}

    - name: Install musl tools for Linux
      if: matrix.os == 'linux-latest'
      run: sudo apt-get update --yes && sudo ap install -y musl-tools

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

    - name: Package as archive
      shell: bash
      run: |
        mkdir -p archives
        ls -al .
        ls -al target
        ls -al target/${{ matrix.target }}
        ls -al target/${{ matrix.target }}/release
        if [[ ${{ matrix.os }} == 'windows-latest' ]]; then
          echo For Windows, use 7z to create a zip archive of raft.exe
          cd target/${{ matrix.target }}/release
          7z a ../../../archives/${{ matrix.asset_name }} ${{ matrix.bin }}
          cd -
          ls -al archives
        else
          echo For Unix-like OSes, use tar to create a gzipped archive of raft
          tar -czf archives/${{ matrix.asset_name }} -C target/${{ matrix.target }}/release ${{ matrix.bin }}
          ls -al archives
        fi

    - name: Publish release artifacts
      uses: actions/upload-artifact@v4
      with:
        name: ${{ matrix.asset_name }}
        path: "archives/${{ matrix.asset_name }}"

    - name: Upload Release Asset
      uses: actions/upload-release-asset@v1
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      with:
        upload_url: ${{ github.event.release.upload_url }}
        asset_path: ./archives/${{ matrix.asset_name }}
        asset_name: ${{ matrix.asset_name }}
        asset_content_type: ${{ matrix.asset_content_type }}
