name: FreeBSD Builds

on:
  workflow_call:
  workflow_dispatch:

jobs:
  build-freebsd:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          submodules: recursive

      - name: Build in FreeBSD
        id: build
        uses: vmactions/freebsd-vm@v1
        with:
          usesh: true
          # rsync is the default, ensuring target/ and archives come back to the host
          sync: rsync
          prepare: |
            pkg install -y rust pkgconf llvm
          run: |
            set -e  # Exit immediately on any error

            # 1. Add swap space to avoid OOM during compilation.
            #    The FreeBSD VM has limited RAM; heavy crates like rquickjs
            #    (bindgen) and oxc can exhaust it when compiled in parallel.
            dd if=/dev/zero of=/swapfile bs=1m count=4096 || true
            chmod 0600 /swapfile
            mdconfig -a -t vnode -f /swapfile -u 0 || true
            swapon /dev/md0 || true

            # 2. Build project with reduced parallelism to limit peak memory.
            #    -j 2 prevents too many concurrent rustc instances.
            CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 cargo build --release --locked -j 2

            # Verify binary was built
            ls -la target/release/fresh

            # 3. Setup Variables
            TARGET="x86_64-unknown-freebsd"
            ARCHIVE_NAME="fresh-editor-${TARGET}"
            mkdir -p "${ARCHIVE_NAME}"

            # 4. Package assets
            cp target/release/fresh "${ARCHIVE_NAME}/"
            cp README.md LICENSE CHANGELOG.md "${ARCHIVE_NAME}/" || true
            # Plugins/themes are embedded in the binary; no on-disk copy needed.
            cp -r docs/icons/linux/hicolor "${ARCHIVE_NAME}/icons" || true
            cp crates/fresh-editor/resources/fresh.desktop "${ARCHIVE_NAME}/fresh.desktop" || true

            # 5. Create Archive
            tar -cJvf "${ARCHIVE_NAME}.tar.xz" "${ARCHIVE_NAME}"
            sha256 -q "${ARCHIVE_NAME}.tar.xz" > "${ARCHIVE_NAME}.tar.xz.sha256"

            # Verify archive contents
            echo "Archive contents:"
            tar -tJf "${ARCHIVE_NAME}.tar.xz" | grep -E '(fresh|README)' | head -5

      - name: Upload artifacts
        uses: actions/upload-artifact@v6
        with:
          name: artifacts-x86_64-unknown-freebsd
          path: |
            fresh-editor-x86_64-unknown-freebsd.tar.xz
            fresh-editor-x86_64-unknown-freebsd.tar.xz.sha256
