{ pkgs
, crane
, system
}:

let
  craneLib = (crane.mkLib pkgs).overrideToolchain pkgs.rustToolchain;

  commonArgs = {
    pname = "prymn_agent-${system}";
    version = "0.1.0";
    nativeBuildInputs = [ pkgs.protobuf ];

    src = pkgs.lib.cleanSourceWith {
      src = craneLib.path ../.;

      filter = path: type:
        (craneLib.filterCargoSources path type) ||
        (builtins.match ".*proto$" path != null);
    };

    CARGO_BUILD_TARGET = targetToTriple system;
    CARGO_BUILD_RUSTFLAGS = "-C target-feature=+crt-static -C linker=rust-lld";
  };

  targetToTriple = targetSystem:
    builtins.replaceStrings
      [ "x86_64-linux" "aarch64-linux" ]
      [ "x86_64-unknown-linux-musl" "aarch64-unknown-linux-musl" ]
      targetSystem;

in
rec {
  cargoArtifacts = craneLib.buildDepsOnly (commonArgs // {
    strictDeps = true;
    doCheck = false; # Tests are run in CI separately
  });

  test = craneLib.cargoTest (commonArgs // {
    inherit cargoArtifacts;
  });

  clippy = craneLib.cargoClippy (commonArgs // {
    inherit cargoArtifacts;

    cargoClippyExtraArgs = "--all-targets -- -D warnings";
  });

  format = craneLib.cargoFmt commonArgs;

  package = targetSystem: craneLib.buildPackage (commonArgs // {
    inherit cargoArtifacts;

    pname = "prymn_agent-${targetSystem}";
    doCheck = false;
    CARGO_BUILD_TARGET = targetToTriple targetSystem;
    CARGO_BUILD_RUSTFLAGS = "-C target-feature=+crt-static -C linker=rust-lld";
  });
}