{
  stdenv,
  fetchFromGitHub,
  lib,
  MODEL ? "5",
  DEBUG ? "0",
  TFA_FLAGS ? "",
}:
let
  inherit (lib.trivial) importJSON;
  versions = importJSON ./versions.json;
in
stdenv.mkDerivation rec {
  pname = "arm-trusted-firmware";
  version = versions.fw.rev;

  src = fetchFromGitHub {
    owner = "ARM-software";
    repo = "arm-trusted-firmware";
    rev = "${version}";
    hash = versions.fw.hash;
  };

  # Add required host tools if needed:
  nativeBuildInputs = [
    # dtc python3 openssl etc.
  ];

  buildPhase = ''
    make \
      CROSS_COMPILE=${stdenv.cc.targetPrefix} \
      CC=${stdenv.cc.targetPrefix}cc \
      AS=${stdenv.cc.targetPrefix}cc \
      PLAT=rpi${MODEL} \
      PRELOADED_BL33_BASE=0x20000 \
      RPI3_PRELOADED_DTB_BASE=0x3E0000 \
      SUPPORT_VFP=1 \
      SMC_PCI_SUPPORT=1 \
      ENABLE_FEAT_VHE=1 \
      DEBUG=${DEBUG} \
      all \
      ${TFA_FLAGS}
  '';

  installPhase = ''
    mkdir -p $out
    cp -r build/* $out/
  '';

  meta = with lib; {
    description = "ARM Trusted Firmware-A for Raspberry Pi";
    license = licenses.bsd3;
    platforms = [ "aarch64-linux" ];
    maintainers = with maintainers; [ kazenyuk ];
  };
}
