# Musl static builds with full features (including plugins).
# rquickjs ships pre-built bindings for musl targets and compiles QuickJS
# statically, so plugins work correctly with musl.

name: Musl Builds

on:
  workflow_call:
  workflow_dispatch:

jobs:
  build-musl:
    strategy:
      fail-fast: false
      matrix:
        include:
          - target: x86_64-unknown-linux-musl
            runner: ubuntu-22.04
          - target: aarch64-unknown-linux-musl
            runner: ubuntu-22.04
    runs-on: ${{ matrix.runner }}
    env:
      GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    steps:
      - uses: actions/checkout@v6
        with:
          persist-credentials: false
          submodules: recursive

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

      # rust-toolchain.toml overrides the targets parameter above, so we need to explicitly add it
      - name: Add target
        run: rustup target add ${{ matrix.target }}

      - name: Install musl tools
        run: |
          sudo apt-get update
          sudo apt-get install -y musl-tools
          # For aarch64 cross-compilation
          if [ "${{ matrix.target }}" = "aarch64-unknown-linux-musl" ]; then
            # Install cross for easier cross-compilation
            cargo install cross --git https://github.com/cross-rs/cross
          fi

      - name: Build release binary
        run: |
          if [ "${{ matrix.target }}" = "aarch64-unknown-linux-musl" ]; then
            cross build --release --target ${{ matrix.target }}
          else
            cargo build --release --target ${{ matrix.target }}
          fi

      - name: Get version from Cargo.toml
        id: version
        run: |
          VERSION=$(grep '^version' Cargo.toml | head -1 | sed 's/.*"\(.*\)".*/\1/')
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"

      - name: Create archive
        run: |
          ARCHIVE_NAME="fresh-editor-${{ matrix.target }}"
          mkdir -p "${ARCHIVE_NAME}"
          cp target/${{ matrix.target }}/release/fresh "${ARCHIVE_NAME}/"
          cp README.md LICENSE "${ARCHIVE_NAME}/" 2>/dev/null || true
          # Plugins/themes are embedded in the binary; no on-disk copy needed.
          cp -r docs/icons/linux/hicolor "${ARCHIVE_NAME}/icons" 2>/dev/null || true
          cp crates/fresh-editor/resources/fresh.desktop "${ARCHIVE_NAME}/fresh.desktop" 2>/dev/null || true

          tar -czvf "${ARCHIVE_NAME}.tar.gz" "${ARCHIVE_NAME}"
          sha256sum "${ARCHIVE_NAME}.tar.gz" > "${ARCHIVE_NAME}.tar.gz.sha256"

          ls -la "${ARCHIVE_NAME}.tar.gz"*

      - name: Upload artifacts
        uses: actions/upload-artifact@v6
        with:
          name: artifacts-musl-${{ matrix.target }}
          path: |
            fresh-editor-${{ matrix.target }}.tar.gz
            fresh-editor-${{ matrix.target }}.tar.gz.sha256
