{
  pkgs,
  lib,
  crane,
  advisory-db,
}:
let
  rustToolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
  craneLib = (crane.mkLib pkgs).overrideToolchain rustToolchain;
  src = craneLib.cleanCargoSource ./.;
  commonArgs = {
    inherit src;
    strictDeps = true;
    buildInputs = [ ];
  };
  cargoArtifacts = craneLib.buildDepsOnly commonArgs;
  individualCrateArgs = commonArgs // {
    inherit cargoArtifacts;
    inherit (craneLib.crateNameFromCargoToml { inherit src; }) version;
    doCheck = false;
  };
  fileSetForCrate =
    crate:
    lib.fileset.toSource {
      root = ./.;
      fileset = lib.fileset.unions [
        ./Cargo.lock
        ./Cargo.toml
        (craneLib.fileset.commonCargoSources ./lib)
        (craneLib.fileset.commonCargoSources ./program/${crate})
      ];
    };
in
{
  buildRustPackage =
    {
      crateName,
      runtimeInputs,
      replacePath ? false,
    }:
    craneLib.buildPackage (
      individualCrateArgs
      // {
        pname = crateName;
        cargoExtraArgs = "-p ${crateName}";
        src = fileSetForCrate crateName;
        nativeBuildInputs = [ pkgs.makeWrapper ];
        postFixup =
          if replacePath then
            ''
              wrapProgram $out/bin/${crateName} --set PATH "${lib.makeBinPath runtimeInputs}"
            ''
          else
            ''
              wrapProgram $out/bin/${crateName} --suffix PATH : "${lib.makeBinPath runtimeInputs}"
            '';
        meta = {
          mainProgram = crateName;
        };
      }
    );
  checks = {
    rust-clippy = craneLib.cargoClippy (
      commonArgs
      // {
        inherit cargoArtifacts;
        cargoClippyExtraArgs = "--all-targets -- --deny warnings";
      }
    );
    rust-doc = craneLib.cargoDoc (
      commonArgs
      // {
        inherit cargoArtifacts;
      }
    );
    rust-fmt = craneLib.cargoFmt (
      commonArgs
      // {
        inherit cargoArtifacts;
      }
    );
    # Not used currently, as I have some other formatter changing toml formatting
    # not sure where it comes from, but I need to find out and decide on a formatter
    rust-toml-fmt = craneLib.taploFmt {
      src = lib.sources.sourceFilesBySuffices src [ ".toml" ];
    };
    rust-audit = craneLib.cargoAudit {
      inherit src advisory-db;
    };
    rust-hakari = craneLib.mkCargoDerivation {
      inherit src;
      pname = "rust-hakari";
      cargoArtifacts = null;
      doInstallCargoArtifacts = false;

      buildPhaseCargoCommand = ''
        cargo hakari generate --diff  # workspace-hack Cargo.toml is up-to-date
        cargo hakari manage-deps --dry-run  # all workspace crates depend on workspace-hack
        cargo hakari verify
      '';

      nativeBuildInputs = [
        pkgs.cargo-hakari
      ];
    };
  };
  devDeps = [
    pkgs.cargo-hakari
    rustToolchain
  ];
}
