{
  static ? false
, system ? builtins.currentSystem
}:

let
  # Pinned Nixpkgs for reproducibility
  nixpkgs = builtins.fetchTarball
    { name = "nixpkgs-23.05.5a237aecb572";
      url = "https://github.com/nixos/nixpkgs/archive/5a237aecb572.tar.gz";
      sha256 = "166yxg4ff2jxvl9mbngd90dr1k3rdj6xmiccga41xynhh2zr0vmb";
    };

  # Exclude this file, .git and more from source
  sieve = path: type:
    !builtins.elem (baseNameOf path) (
      [ "default.nix" ".git" ]
      ++ lib.splitString "\n" (lib.readFile ./.gitignore));

  inherit (import nixpkgs { inherit system; }) lib pkgs;

  python = pkgs.python3;

  gray-python = python.pkgs.buildPythonPackage {
    pname = "gray";
    version = builtins.readFile ./.version;
    src = builtins.filterSource sieve ./.;

    format = "other";
    propagatedBuildInputs = with pkgs.python3Packages; [ numpy scipy matplotlib ];
    makeFlags = [ "PREFIX=$(out)" ];

    dontConfigure = true;
    dontBuild = true;
    installTargets = "install-python";

    pythonImportsCheck = [ "gray" ];

    meta = {
      description = "Python interface to GRAY";
      platforms = python.meta.platforms;
    };
  };

in
  pkgs.stdenv.mkDerivation {
    pname = "gray";
    version = builtins.readFile ./.version;
    src = builtins.filterSource sieve ./.;

    doCheck = true;

    checkInputs = with python.pkgs; [ numpy scipy matplotlib ];

    nativeBuildInputs = with pkgs; [
      # fortran
      gfortran

      # debugging
      makefile2graph graphviz

      # documentation
      help2man pandoc librsvg fontconfig
      haskellPackages.pandoc-crossref
      (texlive.combine {
        inherit (texlive) scheme-small xetex fontspec;
      })

      # save nixpkgs tarball from gc
      nixpkgs
    ];

    buildInputs =
      lib.singleton (python.withPackages (p: [ gray-python ]))
      ++ lib.optional static pkgs.glibc.static;

    # fonts needed for the PDF manual
    env.FONTCONFIG_FILE = pkgs.makeFontsConf
      { fontDirectories = with pkgs; [ libertinus julia-mono ]; };

    preConfigure = ''
      # set directories for temporary files
      export XDG_CACHE_HOME=$NIX_BUILD_TOP
      export XDG_CONFIG_HOME=$NIX_BUILD_TOP
    '';

    enableParallelBuilding = true;

    hardeningDisable = [ "format" ];
    configureFlags = [
      (lib.enableFeature static "static")
      "--enable-deterministic"
    ];

    shellHook = ''
      export PREFIX=build/
      export PYTHONPATH=build/${python.sitePackages}
    '';

    passthru.python = gray-python;

    meta = {
      homepage = "https://doi.org/10.13182/FST07-A1494";
      description = "A quasi-optical beam-tracing code for EC waves in tokamaks";
      platforms = lib.platforms.unix;
      # license?
    };
  }