From d1e1baf15ad6bba5a95f8d0827781351261379dc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Lars=20Sj=C3=B6strom?= <lars@radicore.se>
Date: Wed, 8 Jan 2025 11:09:34 +0100
Subject: [PATCH] chore: build static binaries with musl

---
 flake.nix | 41 +++++++++++++++++++++++++++++++----------
 1 file changed, 31 insertions(+), 10 deletions(-)

diff --git a/flake.nix b/flake.nix
index ac97f6e..8110be1 100644
--- a/flake.nix
+++ b/flake.nix
@@ -27,6 +27,8 @@
       system:
       let
         rustVersion = "1.83.0";
+        target = "x86_64-unknown-linux-musl";
+        isStatic = true;
 
         overlays = [
           (import rust-overlay)
@@ -43,7 +45,24 @@
         ];
 
         pkgs = import nixpkgs { inherit overlays system; };
-        craneLib = (crane.mkLib pkgs).overrideToolchain pkgs.rust-toolchain;
+
+        basePkgs = import nixpkgs (
+          {
+            localSystem = system;
+            overlays = [
+              (import rust-overlay)
+            ];
+          }
+          // pkgs.lib.optionalAttrs isStatic { crossSystem.config = target; }
+        );
+        crossPkgs = (if isStatic then basePkgs.pkgsStatic else basePkgs);
+
+        craneLib = (crane.mkLib crossPkgs).overrideToolchain (
+          p:
+          p.rust-bin.stable.${rustVersion}.default.override {
+            targets = [ target ];
+          }
+        );
 
         src = pkgs.lib.fileset.toSource {
           root = ./.;
@@ -58,19 +77,21 @@
         commonArgs = {
           inherit src;
 
-          stdenv = pkgs.stdenvAdapters.useMoldLinker pkgs.stdenv;
           strictDeps = true;
           cargoArtifacts = craneLib.buildDepsOnly commonArgs;
 
-          nativeBuildInputs = with pkgs; [
-            clang
-            mold-wrapped
-            pkg-config
-          ];
+          nativeBuildInputs = with crossPkgs.pkgsBuildHost; [ pkg-config ];
+          buildInputs = with crossPkgs.pkgsHostHost; [ openssl ];
 
-          buildInputs = with pkgs; [
-            openssl
-          ];
+          CARGO_BUILD_TARGET = target;
+          CARGO_BUILD_RUSTFLAGS = "-C target-feature=+crt-static";
+          "CARGO_TARGET_${pkgs.lib.toUpper (builtins.replaceStrings [ "-" ] [ "_" ] target)}_LINKER" =
+            "${crossPkgs.stdenv.cc.targetPrefix}cc";
+
+          OPENSSL_STATIC = true;
+          OPENSSL_DIR = "${crossPkgs.openssl.dev}";
+          OPENSSL_LIB_DIR = "${crossPkgs.openssl.out}/lib";
+          OPENSSL_INCLUDE_DIR = "${crossPkgs.openssl.dev}/include/";
         };
 
         buildCrate =