# NixOS on SHARP Brain (i.MX28) - build guide

This directory contains a Nix-based build setup for Brain (armv5). It
assumes the following repositories exist in `sources/`:
- `sources/linux-brain-brain` (kernel)
- `sources/buildbrain` (boot tooling + u-boot-brain submodule)

See `docs/brain-bootflow.md` for the boot chain details.

## 0) Model and DTB name
Pick your Brain model and DTB name from:
- `sources/linux-brain-brain/arch/arm/boot/dts/`

Examples:
- PW-SH5 -> `imx28-pwsh5.dtb`
- PW-SH6 -> `imx28-pwsh6.dtb`

DTB selection is done by U-Boot via the `fdtfile` environment variable,
which is set from `CONFIG_DEFAULT_FDT_FILE` in each defconfig. Build the
matching U-Boot defconfig for your model (pwshX / pwa7X00).

## 1) U-Boot with extlinux support (fork + patch)
Patch file:
- `patches/u-boot-brain-extlinux.patch`

Apply it to your fork of `brain-hackers/u-boot-brain` and build
for your model defconfig (pwshX / pwa7X00).

Nix build helper (cross-compiles to armv5):

```sh
nix-build nix/uboot.nix -A pwsh6
```

Output:
- `result/u-boot.bin`

Rename it for BrainLILO:
- `gen3_6.bin` (PW-SH6)

The mapping is defined in:
- `sources/buildbrain/brainlilo/models.h`

## 2) Prepare bootfiles/ (FAT partition contents)
The latest BrainLILO release has already been downloaded and extracted to:
- `bootfiles/アプリ/BrainLILO/`

Create the following layout in `bootfiles/` (PW-SH6 example):

```
bootfiles/
  loader/
    gen3_6.bin
  nk/                     # optional
  アプリ/BrainLILO/
    AppMain.exe
    BrainLILO.dll
    BrainLILODrv.dll
    index.din
```

Notes:
- BrainLILO release binaries are from:
  https://github.com/brain-hackers/brainlilo/releases
- If you prefer the buildbrain layout (`アプリ/Launch Linux`), use
  `sources/buildbrain/image/build_image.sh` as the reference.

## 3) Build the NixOS SD image
Build from this repo root:

```sh
nix-build nix/brain-system.nix -A config.system.build.sdImage
```

The image will be in:
- `result/sd-image/brain-nixos-*.img.bz2`

Flash it to SD:

```sh
bzcat result/sd-image/brain-nixos-*.img.bz2 > /dev/sdX
```

## 4) Boot
- Insert the SD card into the Brain.
- Run BrainLILO from Windows CE (SD card app list).
- U-Boot loads extlinux from the ext4 root partition.

## 5) USB gadget (optional)
To use USB Ethernet gadget:
- Change DTB `dr_mode` from `host` to `peripheral` in `imx28-brain.dtsi`.
- Enable a configfs RNDIS gadget (see `docs/brain-bootflow.md`).
