# Trigger a release when a tag that looks like a version number is pushed.
on:
  push:
    tags:
      - '[0-9]+.*'

name: Release

jobs:
  release:
    name: Release
    permissions:
      contents: write # Needed for creating releases
    runs-on: ${{ matrix.runs-on }}

    strategy:
      fail-fast: false
      matrix:
        include:
          - { target: x86_64-unknown-linux-gnu, runs-on: ubuntu-24.04 }
          - { target: aarch64-unknown-linux-gnu, runs-on: ubuntu-24.04-arm }
          - { target: riscv64gc-unknown-linux-gnu, runs-on: ubuntu-24.04-arm, build: zigbuild }

          - { target: x86_64-unknown-linux-musl, runs-on: ubuntu-24.04, musl: true, args: --features=mimalloc }
          - { target: aarch64-unknown-linux-musl, runs-on: ubuntu-24.04-arm, musl: true, args: --features=mimalloc }
          - { target: riscv64gc-unknown-linux-musl, runs-on: ubuntu-24.04-arm, build: zigbuild, args: --features=mimalloc }
 
    steps:
    - name: Install dependencies
      run: sudo apt-get update && sudo apt-get install -y clang
      if: matrix.build != 'zigbuild'

    - name: Install musl tools
      run: sudo apt-get update && sudo apt-get install -y musl-tools
      if: matrix.musl == true

    - name: Checkout code
      uses: actions/checkout@v6
      with:
        persist-credentials: false

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

    - uses: taiki-e/install-action@cargo-zigbuild
      if: matrix.build == 'zigbuild'
    - uses: mlugg/setup-zig@v2
      if: matrix.build == 'zigbuild'
      with:
        use-cache: false

    - name: Extract release notes
      shell: bash
      run: |
        awk "/## ${GITHUB_REF_NAME}/{flag=1; next} /^## / && flag{exit} flag" CHANGELOG.md >REL.md

    - name: Build stage1
      run: cargo build --release

    - name: Switch to linking with wild
      if: matrix.build != 'zigbuild' # zigbuild ignores this config
      run: |
        mkdir -p "$HOME/.cargo"
        WILD="${PWD}/target/release/wild"
        $WILD --version
        echo -e "[target.${{matrix.target}}]\nlinker = \"clang\"\nrustflags = [\"-Clink-arg=--ld-path=$WILD\"]\n" >>"$HOME/.cargo/config.toml"
        cat "$HOME/.cargo/config.toml"

    - name: Build release binary
      run: cargo ${{matrix.build || 'build' }} ${{matrix.args}} --profile dist --target ${{ matrix.target }}

    - name: Create tarballs
      run: |
        n="wild-linker-${GITHUB_REF_NAME}-${{ matrix.target }}"
        mkdir "$n"
        cp "target/${{ matrix.target }}/dist/wild" "$n"
        cp README.md LICENSE* CHANGELOG.md "$n"
        readelf -p .comment "$n/wild" | grep "Linker: Wild" || echo "::warning::'$n' wasn't linked with wild"
        tar zcf $n.tar.gz $n

    - name: Release
      uses: softprops/action-gh-release@v2
      with:
        body_path: REL.md
        draft: true
        files: |
          wild-linker-*.tar.gz
