mermet: knot: sourcephile.fr: fix secondary
[sourcephile-nix.git] / flake.nix
index 477e1e29dee17ab39a284119d08fc195498f3773..530f9dca654bd9a5423811a3868f8e0dada8c19c 100644 (file)
--- a/flake.nix
+++ b/flake.nix
 {
-# Pin down nixpkgs from github, instead of using global, system or user registries.
-inputs.nixpkgs.url = "github:NixOS/nixpkgs/b69f140a8028e4718bde4e5082f8df38e50b7971";
-#inputs.nixpkgs.url = "flake:nixpkgs";
-inputs.flake-utils.url = "github:numtide/flake-utils";
-inputs.shell = { type = "path"; path = "./shell"; flake = false; };
-inputs.secrets = { type = "path"; path = "./sec"; flake = false; };
-inputs.pass = { type = "path"; path = "./pass"; flake = false; };
-outputs = inputs: let
-  remoteNixpkgsPatches = [
-    { meta.description = "syncoid: fix PATH to let it use sudo";
-      url = "https://github.com/NixOS/nixpkgs/pull/83901.diff";
-      sha256 = "0q2dicmvl3h3hb9xdd870n5hf6lac489p000c7f1r6k70sh2id4l";
-    }
-    { meta.description = "sanoid: fix sanoid.conf generation";
-      url = "https://github.com/NixOS/nixpkgs/pull/83904.diff";
-      sha256 = "Sy9wPmL+Lfl7hMEeXYOEMk3KlfdL21aL92v6MiGajds=";
-    }
-    { meta.description = "nixos/public-inbox: init";
-      url = "https://github.com/NixOS/nixpkgs/pull/77450.diff";
-      sha256 = "13ikg7chpbf6rrg5sngbdb95q3awhdgl4g8vci42xmqyf208hzzd";
-    }
-    { meta.description = "nixos/security.gnupg: provisioning GnuPG-protected secrets through the Nix store";
-      url = "https://github.com/NixOS/nixpkgs/pull/93659.diff";
-      sha256 = "3im5nSrlM32DQUeq0Yp1MHkUcQyLdCGbxfJjgcc9e78=";
-    }
-    { meta.description = "nixos/croc: init";
-      url = "https://github.com/NixOS/nixpkgs/pull/93629.diff";
-      sha256 = "sha256-hzs5Z9cYCo6aNFfylB37W+1neejV4/kVyM1QmqVhVww=";
-    }
-    { meta.description = "dovecot_fts_xapian: 1.3.1 -> 1.3.3";
-      url = "https://github.com/NixOS/nixpkgs/pull/94938.diff";
-      sha256 = "10bjwcwpvq7nnqdpz0n7c61kb3b27v1abyc80pki7d13jmzzjc04";
-    }
-    { meta.description = "transmission: use freeformType on settings";
-      url = "https://github.com/NixOS/nixpkgs/pull/96655.diff";
-      sha256 = "sha256-lRKe8WnGPc8ojaD9W8ZS+NVMhIoGOCOj9njhqQhzaCM";
-    }
-    { meta.description = "tor: improve type-checking and hardening";
-      url = "https://github.com/NixOS/nixpkgs/pull/97740.diff";
-      sha256 = "sha256-ojmDxbGtfsvrUCtjkR7ZynayEGNDLwYl2Ea6yLOQpIk=";
-    }
-    /*
-    { meta.description = "nixos/postfix: add sandbox";
-      url = "https://github.com/NixOS/nixpkgs/pull/93305.diff";
-      sha256 = "sha256-KmoaPj8G4kRlwkBKo/giyST8xQfnjX3OJhh68NKNaRI=";
-    }
-    { meta.description = "nixos/rspamd: add sandbox";
-      url = "https://github.com/NixOS/nixpkgs/pull/93293.diff";
-      sha256 = "sha256-7OfBzJPeGVhHf4ziYLwOpqaYbElCsjLkT4Y/bbCOPx0=";
-    }
-    */
-    { meta.description = "nixos/syncoid: split in multiple systemd services";
-      url = "https://github.com/NixOS/nixpkgs/pull/98455.diff";
-      sha256 = "sha256-vmPzvjwAOSWqfizgDk3l6FrMD2OsG+8UpIkQvOUcXNI=";
-    }
-    { meta.description = "zerobin: update to v1.0.5";
-      url = "https://github.com/NixOS/nixpkgs/pull/98734.diff";
-      sha256 = "sha256-mEFvzR0ymwR7V3bJBnr9fR3GxA1jDfXZXQzo+jc5Nxc=";
-    }
-    /*
-    { meta.description = "apparmor";
-      url = "https://github.com/NixOS/nixpkgs/pull/93457.diff";
-      sha256 = "sha256-JzS6/42AS9f0XUuC8ybw1tR8lpFwOC59BNqYN4mmeVI=";
-    }
-    */
-  ];
-  localNixpkgsPatches = [
-    nixpkgs/patches/apparmor.diff
-    #nixpkgs/patches/zerobin.diff
-    #nixpkgs/patches/gitolite.diff
-    #nixpkgs/patches/tor.diff
-    #nixpkgs/patches/fix-ld-nix.diff
-    #nixpkgs/patches/fix-ld-nix-apparmor.diff
-  ];
-  originPkgs = inputs.nixpkgs.legacyPackages."x86_64-linux";
-  nixpkgs = originPkgs.applyPatches {
-    name = "nixpkgs-patched";
-    src = inputs.nixpkgs;
-    patches = map originPkgs.fetchpatch remoteNixpkgsPatches ++ localNixpkgsPatches;
-    postPatch = ''
-      patch=$(printf '%s\n' ${builtins.concatStringsSep " "
-         (map (p: p.sha256) remoteNixpkgsPatches ++ localNixpkgsPatches)} |
-        sort | sha256sum | cut -c -7)
-      echo "+patch-$patch" >.version-suffix
-    '';
+  inputs = {
+    doom-emacs.follows = "julm-nix/doom-emacs";
+    home-manager.follows = "julm-nix/home-manager";
+    julm-nix.inputs.nixpkgs.follows = "nixpkgs";
+    julm-nix.url = "git+file:///home/julm/work/sourcephile/nix/julm-nix?ref=main";
+    nix-formatter-pack.follows = "julm-nix/nix-formatter-pack";
+    #nixpkgs.follows = "julm-nix/nixpkgs";
+    nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
+    git-hooks.follows = "julm-nix/git-hooks";
   };
-  lib = originPkgs.lib;
-  machines = builtins.mapAttrs (machineName: machineConfig:
-    let cfg = import machineConfig { inherit inputs; }; in
-    import (nixpkgs + "/nixos/lib/eval-config.nix") (cfg // {
-      extraArgs = {
-        inherit machineName inputs;
-        machines = inputs.self.nixosConfigurations;
-      } // (cfg.extraArgs or {});
-      modules = cfg.modules ++ [({pkgs, ...}: {
-        nix.registry.nixpkgs.flake = nixpkgs;
-        nix.package = pkgs.nixFlakes;
-        nix.extraOptions = "experimental-features = nix-command flakes";
-        nixpkgs.overlays = import nixpkgs/overlays.nix;
-        system.nixos.versionSuffix = ".${
-          lib.substring 0 8 (inputs.self.lastModifiedDate or inputs.self.lastModified)}.${
-          inputs.self.shortRev or "dirty"}";
-        system.nixos.revision = lib.mkIf (inputs.self ? rev) inputs.self.rev;
-        # Let 'nixos-version --json' know about the Git revision of this flake.
-        system.configurationRevision = lib.mkIf (inputs.self ? rev) inputs.self.rev;
-        boot.initrd.network.ssh.hostKeys = [ "/root/initrd/ssh.key" ];
-        /*
-        system.configurationRevision =
-          if inputs.self ? rev
-          then inputs.self.rev
-          else throw "Refusing to build from a dirty Git tree!";
-        */
-        programs.ssh.knownHosts = {
-          mermet = {
-            hostNames = [ "mermet" "mermet.sourcephile.fr" ];
-            publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFvKN2sIpH782MFjaOpcty1Hs/T/TPNJpXI08H3O3oxl";
-          };
-          losurdo = {
-            hostNames = [ "losurdo" "losurdo.sourcephile.fr" ];
-            publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHJkAq1T0Dxozt4RPylvWrUmeuejiG+n/owb3ucnWP9F";
-          };
-        };
-      })];
-    }));
-  in
-  {
-    # nix -L build .#nixosConfigurations.${machineName}.config.system.build.toplevel
-    nixosConfigurations = machines {
-      losurdo = machines/losurdo.nix;
-      mermet  = machines/mermet.nix;
-    };
-  }
-  // inputs.flake-utils.lib.eachDefaultSystem (system:
-    #let pkgs = inputs.nixpkgs.legacyPackages.${system}; in
+
+  outputs = inputs:
     let
-      pkgs = import nixpkgs {
-        inherit system;
-        overlays = import nixpkgs/overlays.nix;
+      remoteNixpkgsPatches = import (inputs.julm-nix + "/nixpkgs/patches.nix");
+      localNixpkgsPatches = [
+        #nixpkgs/patches/systemd-coredump.diff
+      ];
+      originPkgs = inputs.nixpkgs.legacyPackages."x86_64-linux";
+      nixpkgsPath = originPkgs.applyPatches {
+        name = "nixpkgs-patched";
+        src = inputs.nixpkgs;
+        patches = map originPkgs.fetchpatch remoteNixpkgsPatches ++ localNixpkgsPatches;
+        postPatch = ''
+          patch=$(printf '%s\n' ${builtins.concatStringsSep " "
+             (map (p: p.sha256) remoteNixpkgsPatches ++ localNixpkgsPatches)} |
+            sort | sha256sum | cut -c -7)
+          echo "-patch-$patch" >.version-suffix
+        '';
       };
-    in {
-    legacyPackages = pkgs;
-    devShell = import ./shell.nix { inherit inputs pkgs; };
-    apps = builtins.mapAttrs (machineName: { config, ... }: let
-      system = config.system.build.toplevel;
-      keygrip = builtins.getAttr machineName {
-        losurdo = "9AA84E6F6D71F9163C46BF396B141A0806219077";
-        mermet  = "89F52A879E0019A966503AFFDE72EEA84CDFA3A7";
-      };
-      target = "root@${config.networking.hostName}.${config.networking.domain}";
-      nixCopyFlags = ["--substitute-on-destination"];
       profile = "/nix/var/nix/profiles/system";
-      in rec {
-      # Example: nix run .#losurdo.switch
-      "switch" = {
-        type = "app";
-        program = (pkgs.writeShellScript "switch" ''
-          set -eux
-          set -o pipefail
-          nix-store --add-root machines/${machineName}.root --indirect --realise ${system}
-          ${pkgs.nixFlakes}/bin/nix copy --to ssh://'${target}' \
-           ${lib.escapeShellArgs nixCopyFlags} ${system}
-          ${sendkeys.program}
-          # Send the SSH key of the initrd
-          gpg --decrypt '${config.security.gnupg.store}/initrd/ssh.key.gpg' |
-          ssh '${target}' install -D -m 400 -o root -g root /dev/stdin /root/initrd/ssh.key
-          # Send the Wireguard key of the initrd
-          gpg --decrypt '${config.security.gnupg.store}/wireguard/wg-intra/privateKey.gpg' |
-          ssh '${target}' install -D -m 400 -o root -g root /dev/stdin /root/initrd/wg-intra.key
-          ssh '${target}' \
-            nix-env --profile '${profile}' --set '${system}' '&&' \
-            '${profile}'/bin/switch-to-configuration switch
-        '').outPath;
-      };
-      # Example: nix run .#losurdo.sendkeys
-      "sendkeys" = {
-        type = "app";
-        program = (pkgs.writeShellScript "sendkeys" ''
-          set -eux
-          set -o pipefail
-          ssh '${target}' \
-            ${pkgs.gnupg}/bin/gpg-connect-agent --no-autostart --homedir /var/lib/gnupg "'keyinfo --list'" /bye 2>&1 |
-          grep -qx -e "gpg-connect-agent: no gpg-agent running in this session" \
-                   -e "S KEYINFO ${keygrip} . . . 1 .*" || {
-            # Send the GnuPG root key
-            gpg --decrypt '${config.security.gnupg.store}/root/key.pass.gpg' |
-            gpg --batch --pinentry-mode loopback --passphrase-fd 0 --export-secret-subkeys @root@${machineName} |
-            ssh '${target}' \
-              gpg --no-autostart --homedir /var/lib/gnupg --no-autostart --batch --pinentry-mode loopback --import
+      inherit (inputs.nixpkgs) lib;
+      overlays = system:
+        [
+          (finalPkgs: previousPkgs: { }
+          )
+        ] ++
+        import (inputs.julm-nix + "/nixpkgs/overlays.nix") ++
+        import nixpkgs/overlays.nix;
+      #nixosSystem = lib.nixosSystem;
+      nixosSystem = import (nixpkgsPath + "/nixos/lib/eval-config.nix");
+      forAllSystems = f: lib.genAttrs lib.systems.flakeExposed (system: f rec {
+        inherit system;
+        #pkgs = inputs.nixpkgs.legacyPackages.${system};
+        pkgs = import nixpkgsPath { inherit system; overlays = overlays system; };
+      });
+    in
+    {
+      # nix -L build .#hello
+      packages = forAllSystems (args: with args; pkgs);
 
-            # Send the GnuPG root key's passphrase
-            gpg --decrypt '${config.security.gnupg.store}/root/key.pass.gpg' |
-            ssh '${target}' \
-              gpg-preset-passphrase --homedir /var/lib/gnupg --preset ${keygrip}
+      # nix -L build .#nixosConfigurations.mermet.config.system.build.toplevel
+      # nix -L build .#nixosConfigurations.mermet.config.boot.kernelPackages.kernel.configfile
+      # nix -L build .#nixosConfigurations.mermet.pkgs.hello
+      # nix eval --raw .#nixosConfigurations.mermet.config.networking.nftables.ruleset
+      nixosConfigurations = lib.genAttrs
+        (builtins.attrNames (lib.filterAttrs (_n: v: v == "directory") (builtins.readDir (inputs.self + "/hosts"))))
+        (hostName: nixosSystem
+          {
+            system = null;
+            specialArgs = {
+              # Required to avoid infinite recursion
+              # when `inputs` is used in `imports`.
+              inherit inputs;
+            };
+            modules = [
+              nixos/default.nix
+              (inputs.julm-nix + "/nixos/default.nix")
+              (inputs.self + "/hosts/${hostName}.nix")
+              ({ config, ... }: {
+                _module.args = {
+                  inherit hostName;
+                  hosts = inputs.self.nixosConfigurations;
+                  host = inputs.self.nixosConfigurations.${hostName}._module.args;
+                  info = import ./info.nix;
+                };
+                nixpkgs.overlays = overlays config.nixpkgs.hostPlatform.system;
+                #nixpkgs.buildPlatform = "x86_64-linux";
+                nixpkgs.config.allowUnfreePredicate = pkg: builtins.elem (lib.getName pkg) [ "hplip" ];
+              })
+              inputs.nixpkgs.nixosModules.notDetected
+              inputs.home-manager.nixosModules.home-manager
+              {
+                home-manager.useGlobalPkgs = true;
+                home-manager.useUserPackages = true;
+                home-manager.verbose = true;
+                home-manager.backupFileExtension = null;
+                home-manager.extraSpecialArgs = {
+                  inherit hostName inputs;
+                };
+              }
+              {
+                programs.ssh.knownHosts = {
+                  carotte = {
+                    extraHostNames = [ "carotte" "carotte.sourcephile.fr" ];
+                    publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKnnS0w9zm5KuWwlfJu+qEXC0asESQySPp76szyMTE3J";
+                  };
+                  mermet = {
+                    extraHostNames = [ "mermet" "mermet.sourcephile.fr" ];
+                    publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFvKN2sIpH782MFjaOpcty1Hs/T/TPNJpXI08H3O3oxl";
+                  };
+                  losurdo = {
+                    extraHostNames = [ "losurdo" "losurdo.sourcephile.fr" ];
+                    publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHJkAq1T0Dxozt4RPylvWrUmeuejiG+n/owb3ucnWP9F";
+                  };
+                };
+              }
+            ];
           }
-        '').outPath;
-      };
-    }) inputs.self.nixosConfigurations;}
-  );
+        );
+
+      # nix -L develop  or  direnv allow
+      devShell = forAllSystems ({ pkgs, system, ... }: pkgs.callPackage ./shell.nix
+        {
+          inherit pkgs inputs system nixpkgsPath;
+          inherit (inputs.self.checks.${system}.git-hooks-check) shellHook;
+        });
+
+      # nix -L run .#mermet.switch
+      apps = forAllSystems ({ pkgs, system, ... }:
+        with builtins;
+        mapAttrs
+          (hostName: { config, pkgs, ... }:
+            let
+              inherit (config.system) build;
+              scriptApp = scriptName: ps: script: {
+                type = "app";
+                program = (pkgs.writeShellScript "${hostName}-${scriptName}" ''
+                  export PATH="${lib.makeBinPath ([ pkgs.buildPackages.coreutils ] ++ ps)}:$PATH"
+                  set -eux
+                  ${script}
+                '').outPath;
+              };
+            in
+            {
+              # Example: nix run .#mermet.switch
+              "switch" = scriptApp "switch" [ ] (
+                ''
+                  set -o pipefail
+                  shopt -s globstar
+
+                  chmod -R g-rwx,o-rwx **/*.gpg
+                  trap 'git reset **/*.gpg' EXIT
+                  git rm -rf --cached --ignore-unmatch **/*.gpg # prevent copying to /nix/store
+
+                  nix-store --add-root hosts/${hostName}.nixpkgs --indirect --realise ${nixpkgsPath}
+                  nix-store --add-root hosts/${hostName}.root --indirect --realise ${build.toplevel}
+
+                  nix copy --to ssh://${config.install.target}${lib.optionalString config.install.substituteOnDestination " --substitute-on-destination"} ${build.toplevel}
+
+                  ${config.security.initrd.install}
+
+                  if ssh ${config.install.target} set -x ';' \
+                    systemctl reset-failed nixos-fallback '2>/dev/null' ';' \
+                    test "''${NO_NIXOS_FALLBACK:+set}" '||' \
+                    systemd-run -u nixos-fallback --description=nixos-fallback /bin/sh -xc '''\'''
+                      PATH=${with pkgs; lib.makeBinPath [ coreutils nix systemd ]}
+                      sleep $((10 * 60))
+                      ${profile}/bin/switch-to-configuration switch
+                      systemctl reboot
+                    '\'''' '&&' \
+                    ${build.toplevel}/bin/switch-to-configuration test
+                  then
+                    ssh ${config.install.target} -o ControlPath=none set -x ';' \
+                      systemctl stop nixos-fallback.service ';' \
+                      nix-env --profile ${profile} --set '${build.toplevel}' ';' \
+                      ${build.toplevel}/bin/switch-to-configuration boot '&&' \
+                      nix-env --delete-generations 7d --profile ${profile}
+                  else
+                    tput rev
+                    echo WARNING: switch-to-configuration was not registered at boot
+                    tput sgr0
+                    ssh ${config.install.target} -o ControlPath=none set -x ';' \
+                      systemctl stop nixos-fallback.service
+                    false
+                  fi
+                ''
+              );
+              # Example: nix run .#carotte.install-sd
+              # DELETEME: quite useless, better to use nixos-install
+              "install-sd" = scriptApp "install-sd" [ pkgs.zstd ] ''
+                set -o pipefail
+                nix-store --add-root hosts/${hostName}.root --indirect --realise ${build.sdImage}
+                unzstd --stdout ${build.sdImage}/sd-image/*.img.zst |
+                sudo -k dd conv=notrunc oflag=direct,sync status=progress of="''${1:-/dev/mmcblk0}"
+              '';
+            }
+          )
+          inputs.self.nixosConfigurations
+      );
+
+      # nix flake check
+      checks = forAllSystems (args: with args; {
+        git-hooks-check = inputs.git-hooks.lib.${system}.run {
+          src = inputs.self;
+          hooks = {
+            nixpkgs-fmt.enable = true;
+          };
+        };
+      });
+
+      # nix fmt
+      formatter = forAllSystems ({ pkgs, ... }:
+        inputs.nix-formatter-pack.lib.mkFormatter {
+          inherit pkgs;
+          config = {
+            tools = {
+              deadnix.enable = true;
+              nixfmt-rfc-style.enable = true;
+              statix.enable = true;
+            };
+          };
+        }
+      );
+
+    };
 }