From e4d8bfada58057123ac11e3848cf363bdcc7c9a9 Mon Sep 17 00:00:00 2001
From: Wroclaw <wroclaw223@outlook.com>
Date: Mon, 24 Feb 2025 12:54:04 +0100
Subject: [PATCH] nixos/nix-binary-cache: create nix cache signing key if
 doesn't exists

---
 nix-os/services/nix-binary-cache.nix | 45 +++++++++++++++++++++++++++-
 1 file changed, 44 insertions(+), 1 deletion(-)

diff --git a/nix-os/services/nix-binary-cache.nix b/nix-os/services/nix-binary-cache.nix
index 923b0bc..3dd7ad6 100644
--- a/nix-os/services/nix-binary-cache.nix
+++ b/nix-os/services/nix-binary-cache.nix
@@ -1,11 +1,54 @@
-{ pkgs, ... }:
+{
+  config,
+  lib,
+  pkgs,
+  ...
+}:
 
 {
+  options = {
+    services.nix-serve = {
+      keyName = lib.mkOption {
+        type = lib.types.str;
+        default = config.networking.fqdnOrHostName;
+        defaultText = "config.networking.fqdnOrHostName";
+        description = "Name of the key when generating (usually domain name)";
+      };
+      publicKeyFile = lib.mkOption {
+        type = lib.types.path;
+        default = "/var/cache-pub-key.pem";
+        description = "Path to the public key file";
+      };
+    };
+  };
   config = {
     services.nix-serve = {
       enable = true;
       package = pkgs.nix-serve-ng;
       secretKeyFile = "/var/cache-priv-key.pem";
     };
+    systemd.services.nix-serve-generate-key = let
+      inherit (config.services.nix-serve) keyName secretKeyFile publicKeyFile;
+    in {
+      description = "Ensure existence of nix binary cache signing key";
+      wantedBy = [ config.systemd.services.nix-serve.name ];
+      script = ''
+        if [ -f ${secretKeyFile} ]; then
+          echo "File ${secretKeyFile} already exists, nothing to do" >&2
+          exit 0
+        fi
+        if [ -a ${secretKeyFile} ]; then
+          echo "File ${secretKeyFile} is not a regular file" >&2
+          exit 1
+        fi
+        echo "Generating nix binary cache signing key" >&2
+        touch ${secretKeyFile}
+        chmod 600 ${secretKeyFile}
+        mkdir -p $(dirname ${secretKeyFile})
+        ${lib.getExe' pkgs.nix "nix-store"} --generate-binary-cache-key \
+          ${keyName} ${secretKeyFile} ${publicKeyFile}
+      '';
+      restartIfChanged = true;
+    };
   };
 }