# Open replacement firmware for the Apple Video Decoder.
# Built from AsahiLinux sources, without extracting proprietary firmware.

pkgname=avd-fw
pkgver=0.1
pkgrel=1
pkgdesc='Open replacement firmware for the Apple Video Decoder (AVD) on Apple Silicon'
# This recipe uses the native ARM linker and serves Apple Silicon systems.
# Restrict both builds and publication to aarch64.
arch=('aarch64')
url='https://github.com/AsahiLinux/avd-fw'
license=('MIT')
# clang cross-compiles to arm-none-eabi out of the box, so no arm-none-eabi
# toolchain is required; llvm supplies llvm-objcopy, which meson.build looks
# up by name to turn each linked ELF into a padded raw image.
makedepends=('meson' 'clang' 'llvm')
# !buildflags is load-bearing: makepkg's CFLAGS/LDFLAGS target the aarch64 host
# and would be injected into a bare-metal Cortex-M3 build. !strip keeps makepkg
# from running the host strip over raw firmware images.
options=('!strip' '!debug' '!buildflags' '!lto')
source=("$pkgname-$pkgver.tar.gz::$url/archive/refs/tags/v$pkgver.tar.gz")
sha256sums=('2e131244275cb15c94243e41eec8a2a665ec895cfe3a818181549db991e62c67')

build() {
  # The cross file selects clang, pins the host machine to cortex-m3 and sets
  # libdir=lib, which lands the images in /usr/lib/firmware/apple.
  #
  # Optimization is pinned to match upstream's Makefile (-O2). Meson's default
  # buildtype is "debug" (-O0 -g), which would ship unoptimized firmware; the
  # MMIO accessors in src/util.c go through a volatile typedef, so -O2 cannot
  # elide register reads or writes.
  meson setup \
    --cross-file "$pkgname-$pkgver/llvm.ini" \
    --prefix=/usr \
    -Doptimization=2 \
    -Ddebug=false \
    "$pkgname-$pkgver" build

  meson compile -C build
}

package() {
  meson install -C build --destdir "$pkgdir"

  # meson installs custom_target outputs 0755; these are firmware blobs, not
  # programs, and every other firmware file on the system is 0644.
  chmod 644 "$pkgdir"/usr/lib/firmware/apple/*.bin

  install -Dm644 "$pkgname-$pkgver/LICENSE" \
    "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
}
