{ config, lib, pkgs, ... }:

with lib;
let
  cfg = config.my.profiles.impermanence;
in
{
  options.my.profiles.impermanence.enable = mkEnableOption "impermanence";

  config = mkIf cfg.enable {
    age.secrets = {
      root-password.file = ../../secrets/root-password.age;
      moritz-password.file = ../../secrets/moritz-password.age;
    };
    users.users = {
      root.hashedPasswordFile = config.age.secrets.root-password.path;
      moritz.hashedPasswordFile = config.age.secrets.moritz-password.path;
    };
    users.mutableUsers = false;
    environment.persistence."/persist" = {
      hideMounts = true;
      directories = [
        "/etc/NetworkManager/system-connections"
        "/var/db/dhcpcd/"
        "/var/lib/NetworkManager/"
        "/var/lib/bluetooth"
        "/var/lib/nixos"
        "/var/lib/systemd"
        "/var/log"
      ];
      files = [
        "/etc/machine-id"
        "/etc/nix/id_rsa"
        "/etc/ssh/ssh_host_ed25519_key"
        "/etc/ssh/ssh_host_ed25519_key.pub"
        "/etc/ssh/ssh_host_rsa_key"
        "/etc/ssh/ssh_host_rsa_key.pub"
      ];
      users.moritz = {
        directories = [
          ".SynologyDrive/data"
          ".SynologyDrive/log"
          ".cache/keepassxc"
          ".cache/nvim/luac"
          ".cat_installer" # eduroam
          ".config/JetBrains"
          ".config/Nextcloud"
          ".config/calibre"
          ".config/github-copilot"
          ".config/kdeconnect"
          ".config/keepassxc"
          ".java/.userPrefs/jetbrains/"
          ".local/share/JetBrains"
          ".local/share/direnv"
          ".local/share/nvim"
          ".local/share/zoxide"
          ".local/state/nvim"
          ".mozilla"
          "Documents"
          "Downloads"
          "Music"
          "Pictures"
          "Videos"
          { directory = ".gnupg"; mode = "0700"; }
          { directory = ".local/share/keyrings"; mode = "0700"; }
          { directory = ".ssh"; mode = "0700"; }
        ];
        files = [
          ".local/share/fish/fish_history"
          ".local/share/nix/trusted-settings.json"
          ".parallel/will-cite"
          ".local/state/tofi-history"
        ];
      };
      users.root = {
        home = "/root";
        directories = [
          { directory = ".gnupg"; mode = "0700"; }
          { directory = ".ssh"; mode = "0700"; }
        ];
        files = [
          ".local/share/nix/trusted-settings.json"
        ];
      };
    };

    environment.systemPackages = [
      (
        pkgs.writeShellApplication {
          name = "zfs-diff";
          runtimeInputs = with pkgs; [ zfs coreutils parallel tree ];
          text = ''
            zfs diff -F zroot/encrypted/root@blank | awk '$2 == "F" && system("test -e /persist/"$3) != 0 { print $3 }' 2>/dev/null | tree --fromfile . "$@"
          '';
        }
      )
    ];
  };
}
