{
  fetchFromGitHub,
  lib,
  pkgs,
  stdenv,
  targetPackages,
  ...
}:
let
  version = "257.3";

  # Use the command below to update `releaseTimestamp` on every (major) version
  # change. More details in the commentary at mesonFlags.
  # command:
  #  $ curl -s https://api.github.com/repos/systemd/systemd/releases/latest | \
  #     jq '.created_at|strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'
  releaseTimestamp = "1734643670";

  pname = "systemd";
in
stdenv.mkDerivation (finalAttrs: {
  inherit version;

  pname = pname;

  src = fetchFromGitHub {
    owner = "systemd";
    repo = "systemd";
    rev = "v${version}";
    hash = "sha256-GvRn55grHWR6M+tA86RMzqinuXNpPZzRB4ApuGN/ZvU=";
  };

  dontCheckForBrokenSymlinks = true;

  patches = [
    ./0017-meson.build-do-not-create-systemdstatedir.patch
  ];

  nativeBuildInputs = with pkgs; [
    bash
    pkg-config
    makeBinaryWrapper
    gperf
    ninja
    meson
    glibcLocales
    getent
    m4
    autoPatchelfHook

    intltool
    gettext

    libxslt
    docbook_xsl
    docbook_xml_dtd_42
    docbook_xml_dtd_45
    bash
    (buildPackages.python3Packages.python.withPackages (
      ps: with ps; [
        lxml
        jinja2
        ps.pyelftools
      ]
    ))

    bpftools
    buildPackages.llvmPackages.clang
    buildPackages.llvmPackages.libllvm
  ];

  outputs = [
    "out"
    "dev"
  ];

  separateDebugInfo = true;

  autoPatchelfFlags = [ "--keep-libc" ];

  hardeningDisable = [
    # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111523
    "trivialautovarinit"
    # breaks clang -target bpf; should be fixed to filter target?
    "zerocallusedregs"
    "shadowstack"
  ];

  buildInputs = with pkgs; [
    libxcrypt
    libcap
    libuuid
    linuxHeaders
    bashInteractive # for patch shebangs
    libgcrypt
    libgpg-error
    openssl
    acl
    libapparmor
    audit
    zlib
    bzip2
    lz4
    xz
    zstd
    elfutils
    kexec-tools
    kmod
    libidn2
    libseccomp
    libselinux
    iptables
    p11-kit
    libfido2
    pam
    pcre2
    libbpf
    tpm2-tss
    qrencode
    libarchive
    (lib.getDev curl)
    (lib.getDev cryptsetup.dev)
    (python3Packages.python.withPackages (ps: with ps; [ pefile ]))
    (llvmPackages.compiler-rt.override {
      doFakeLibgcc = true;
    })
  ];

  mesonBuildType = "release";

  doCheck = false; # fails a bunch of tests

  preConfigure = ''
    mesonFlagsArray+=(-Dntp-servers="0.europe.pool.ntp.org 1.europe.pool.ntp.org 2.europe.pool.ntp.org 3.europe.pool.ntp.org")
    export LC_ALL="en_US.UTF-8";
  '';

  postPatch =
    ''
      substituteInPlace meson.build \
        --replace "find_program('clang'" "find_program('${stdenv.cc.targetPrefix}clang'"
    ''
    + ''
      substituteInPlace src/ukify/ukify.py \
        --replace \
        "'readelf'" \
        "'${targetPackages.stdenv.cc.bintools.targetPrefix}readelf'" \
        --replace \
        "/usr/lib/systemd/boot/efi" \
        "$out/usr/lib/systemd/boot/efi"
    ''
    # Finally, patch shebangs in scripts used at build time. This must not patch
    # scripts that will end up in the output, to avoid build platform references
    # when cross-compiling.
    + ''
      shopt -s extglob
      patchShebangs tools test src/!(rpm|kernel-install|ukify) src/kernel-install/test-kernel-install.sh
    '';

  # trigger the test -n "$DESTDIR" || mutate in upstreams build system
  preInstall = ''
    export DESTDIR=${placeholder "out"}
  '';

  mesonFlags = [

    "--prefix=/usr"
    "--sysconfdir=/etc"
    "--localstatedir=/var"
    "--libdir=/usr/lib"
    "--bindir=/usr/bin"
    "--includedir=/usr/include"
    "--localedir=/usr/share/locale"

    # Options

    # We bump this attribute on every (major) version change to ensure that we
    # have known-good value for a timestamp that is in the (not so distant)
    # past. This serves as a lower bound for valid system timestamps during
    # startup. Systemd will reset the system timestamp if this date is +- 15
    # years from the system time.
    # See the systemd v250 release notes for further details:
    #   https://github.com/systemd/systemd/blob/60e930fc3e6eb8a36fbc184773119eb8d2f30364/NEWS#L258-L266
    (lib.mesonOption "time-epoch" releaseTimestamp)

    (lib.mesonOption "version-tag" version)
    (lib.mesonOption "mode" "release")
    (lib.mesonOption "tty-gid" "3") # tty in NixOS has gid 3

    (lib.mesonOption "kmod-path" "/usr/bin/kmod")
    (lib.mesonOption "debug-shell" "/usr/bin/sh")
    (lib.mesonOption "pamconfdir" "/etc/pam.d")
    (lib.mesonOption "shellprofiledir" "/etc/profile.d")
    (lib.mesonOption "dbuspolicydir" "/usr/share/dbus-1/system.d")
    (lib.mesonOption "dbussessionservicedir" "/usr/share/dbus-1/services")
    (lib.mesonOption "dbussystemservicedir" "/usr/share/dbus-1/system-services")
    (lib.mesonOption "setfont-path" "/usr/bin/setfont")
    (lib.mesonOption "loadkeys-path" "/usr/bin/loadkeys")
    (lib.mesonOption "sulogin-path"  "/usr/bin/sulogin")
    (lib.mesonOption "nologin-path" "/usr/bin/nologin")
    (lib.mesonOption "mount-path" "/usr/bin/mount")
    (lib.mesonOption "umount-path" "/usr/bin/umount")

    # SBAT
    (lib.mesonOption "sbat-distro" "patos")
    (lib.mesonOption "sbat-distro-summary" "PatOS")
    (lib.mesonOption "sbat-distro-url" "https://patagia.io/")
    (lib.mesonOption "sbat-distro-pkgname" pname)
    (lib.mesonOption "sbat-distro-version" version)

    # Users
    (lib.mesonOption "system-uid-max" "999")
    (lib.mesonOption "system-gid-max" "999")

    # SysVinit
    (lib.mesonOption "sysvinit-path" "")
    (lib.mesonOption "sysvrcnd-path" "")

    # SSH
    # Disabled for now until someone makes this work.
    (lib.mesonOption "sshconfdir" "no")
    (lib.mesonOption "sshdconfdir" "no")

    # Features

    # Tests
    (lib.mesonBool "tests" false)
    (lib.mesonEnable "glib" false)
    (lib.mesonEnable "dbus" false)

    # Compression
    (lib.mesonEnable "bzip2" true)
    (lib.mesonEnable "lz4" true)
    (lib.mesonEnable "xz" true)
    (lib.mesonEnable "zstd" true)
    (lib.mesonEnable "zlib" true)

    # NSS
    (lib.mesonEnable "nss-resolve" true)
    (lib.mesonBool "nss-myhostname" true)
    (lib.mesonBool "nss-systemd" true)

    # Cryptsetup
    (lib.mesonEnable "libcryptsetup" true)
    (lib.mesonEnable "libcryptsetup-plugins" true)
    (lib.mesonEnable "p11kit" true)

    # FIDO2
    (lib.mesonEnable "libfido2" true)
    (lib.mesonEnable "openssl" true)

    # Password Quality
    (lib.mesonEnable "pwquality" false)
    (lib.mesonEnable "passwdqc" false)

    # Remote
    (lib.mesonEnable "remote" false)
    (lib.mesonEnable "microhttpd" false)

    (lib.mesonEnable "pam" false)
    (lib.mesonEnable "acl" true)
    (lib.mesonEnable "audit" true)
    (lib.mesonEnable "apparmor" true)
    (lib.mesonEnable "gcrypt" true)
    (lib.mesonEnable "importd" true)
    (lib.mesonEnable "homed" false)
    (lib.mesonEnable "polkit" true)
    (lib.mesonEnable "elfutils" true)
    (lib.mesonEnable "libcurl" true)
    (lib.mesonEnable "libidn" false)
    (lib.mesonEnable "libidn2" true)
    (lib.mesonEnable "libiptc" true)
    (lib.mesonEnable "repart" true)
    (lib.mesonEnable "sysupdate" true)
    (lib.mesonEnable "sysupdated" true)
    (lib.mesonEnable "seccomp" true)
    (lib.mesonEnable "selinux" true)
    (lib.mesonEnable "tpm2" true)
    (lib.mesonEnable "pcre2" true)
    (lib.mesonEnable "bpf-framework" true)
    (lib.mesonEnable "bootloader" true)
    (lib.mesonEnable "ukify" true)
    (lib.mesonEnable "kmod" true)
    (lib.mesonEnable "qrencode" true)
    (lib.mesonEnable "vmspawn" false)
    (lib.mesonEnable "libarchive" true)
    (lib.mesonEnable "xenctrl" false)
    (lib.mesonEnable "gnutls" false)
    (lib.mesonEnable "xkbcommon" false)
    (lib.mesonEnable "man" false)

    (lib.mesonBool "analyze" true)
    (lib.mesonBool "logind" true)
    (lib.mesonBool "localed" false)
    (lib.mesonBool "hostnamed" true)
    (lib.mesonBool "machined" true)
    (lib.mesonBool "networkd" true)
    (lib.mesonBool "oomd" true)
    (lib.mesonBool "portabled" true)
    (lib.mesonBool "hwdb" true)
    (lib.mesonBool "timedated" true)
    (lib.mesonBool "timesyncd" true)
    (lib.mesonBool "userdb" false)
    (lib.mesonBool "coredump" true)
    (lib.mesonBool "firstboot" true)
    (lib.mesonBool "resolve" true)
    (lib.mesonBool "sysusers" true)
    (lib.mesonBool "efi" true)
    (lib.mesonBool "utmp" true)
    (lib.mesonBool "log-trace" true)

    (lib.mesonBool "kernel-install" true)
    (lib.mesonBool "quotacheck" false)
    (lib.mesonBool "ldconfig" false)
    (lib.mesonBool "install-sysconfdir" true)
    (lib.mesonBool "create-log-dirs" true)
    (lib.mesonBool "smack" true)
    (lib.mesonBool "b_pie" true)

    (lib.mesonOption "bashcompletiondir" "no")
    (lib.mesonOption "zshcompletiondir" "no")
  ];

})