{
  pkgs,
  config,
  inputs,
  lib,
  ...
}: {
  facter.reportPath = ./facter.json;

  fileSystems = {
    "/" = {
      device = "/dev/disk/by-uuid/d375c3a3-63a3-47f8-8b77-58fabbb8f67b";
      fsType = "btrfs";
      options = ["subvol=root"];
    };

    "/home" = {
      device = "/dev/disk/by-uuid/d375c3a3-63a3-47f8-8b77-58fabbb8f67b";
      fsType = "btrfs";
      options = ["subvol=home" "compress=zstd"];
    };

    "/nix" = {
      device = "/dev/disk/by-uuid/d375c3a3-63a3-47f8-8b77-58fabbb8f67b";
      fsType = "btrfs";
      options = ["subvol=nix" "compress=zstd" "noatime"];
    };

    "/persist" = {
      device = "/dev/disk/by-uuid/d375c3a3-63a3-47f8-8b77-58fabbb8f67b";
      neededForBoot = true;
      fsType = "btrfs";
      options = ["subvol=persist" "compress=zstd"];
    };

    "/var/log" = {
      device = "/dev/disk/by-uuid/d375c3a3-63a3-47f8-8b77-58fabbb8f67b";
      fsType = "btrfs";
      options = ["subvol=log" "compress=zstd" "noatime"];
      neededForBoot = true;
    };

    "/boot" = {
      device = "/dev/disk/by-uuid/12CE-A600";
      fsType = "vfat";
      options = ["fmask=0022" "dmask=0022"];
    };
  };

  security = {
    rtkit.enable = true;

    pam = {
      services.login.enableGnomeKeyring = true;

      loginLimits = [
        {
          domain = "*";
          item = "nofile";
          type = "-";
          value = "32768";
        }
        {
          domain = "*";
          item = "memlock";
          type = "-";
          value = "32768";
        }
      ];
    };

    sudo-rs = {
      enable = true;
      wheelNeedsPassword = false;
      execWheelOnly = true;
    };

    tpm2 = {
      enable = true;
      pkcs11.enable = true;
      tctiEnvironment.enable = true;
    };
  };

  fonts = {
    packages = with pkgs;
      [
        ibm-plex
        recursive
      ]
      ++ (with nerd-fonts; [
        _0xproto
        _3270
        agave
        anonymice
        arimo
        aurulent-sans-mono
        bigblue-terminal
        bitstream-vera-sans-mono
        blex-mono
        caskaydia-cove
        caskaydia-mono
        code-new-roman
        comic-shanns-mono
        commit-mono
        cousine
        d2coding
        daddy-time-mono
        dejavu-sans-mono
        departure-mono
        droid-sans-mono
        envy-code-r
        fantasque-sans-mono
        fira-code
        fira-mono
        geist-mono
        go-mono
        gohufont
        hack
        hasklug
        heavy-data
        hurmit
        im-writing
        inconsolata
        inconsolata-go
        inconsolata-lgc
        intone-mono
        iosevka
        iosevka-term
        iosevka-term-slab
        jetbrains-mono
        lekton
        liberation
        lilex
        martian-mono
        meslo-lg
        monaspace
        monofur
        monoid
        mononoki
        mplus
        noto
        open-dyslexic
        overpass
        profont
        proggy-clean-tt
        recursive-mono
        roboto-mono
        sauce-code-pro
        shure-tech-mono
        space-mono
        symbols-only
        terminess-ttf
        tinos
        ubuntu
        ubuntu-mono
        ubuntu-sans
        victor-mono
        zed-mono
      ])
      ++ (with iosevka-comfy; [
        comfy
        comfy-duo
        comfy-fixed
        comfy-motion
        comfy-motion-duo
        comfy-motion-fixed
        comfy-wide
        comfy-wide-duo
        comfy-wide-fixed
        comfy-wide-motion
        comfy-wide-motion-duo
        comfy-wide-motion-fixed
      ]);

    fontconfig = {
      hinting.enable = true;
      subpixel.lcdfilter = "none";
    };
  };

  console.catppuccin.enable = true;

  systemd = {
    tpm2.enable = true;

    user.extraConfig = let
      path = lib.concatStringsSep ":" [
        "/run/wrappers/bin"
        "/etc/profiles/per-user/%u/bin"
        "/nix/var/nix/profiles/default/bin"
        "/run/current-system/sw/bin"
      ];
    in ''
      DefaultEnvironment="PATH=${path}"
    '';
  };

  age = {
    secrets.passwd.file = ../../../secrets/passwd.age;
    identityPaths = ["/persist/root/.ssh/id_ed25519"];
  };

  virtualisation = {
    spiceUSBRedirection.enable = true;
    waydroid.enable = true;

    podman = {
      enable = true;
      dockerCompat = true;
      dockerSocket.enable = true;
    };
  };

  environment = {
    sessionVariables = {
      COSMIC_DATA_CONTROL_ENABLED = 1;
      BROWSER = "zen-bin";
      DIRENV_WARN_TIMEOUT = "100s";
      EDITOR = "nvim";
      NIXOS_OZONE_WL = 1;
      TERMINAL = "wezterm";
    };

    systemPackages = with pkgs; [
      ddccontrol-db
      inputs.agenix.packages.${system}.default
      looking-glass-client
      nautilus
      qemu
      snowfallorg.flake
      sound-theme-freedesktop
      uutils-coreutils-noprefix
      virtio-win
      (warp-terminal.override {waylandSupport = true;})
      winetricks
      wineWowPackages.staging
      xclip
      yt-dlp
    ];

    persistence."/persist" = {
      hideMounts = true;
      directories = [
        "/etc/ssh"
        "/root/.ssh"
        "/var/lib/bluetooth"
        "/var/lib/iwd"
        "/var/lib/libvirt"
        "/var/lib/nixos"
        "/var/lib/systemd/coredump"
      ];
      files = ["/etc/machine-id"];
    };
  };

  boot = {
    blacklistedKernelModules = ["nouveau" "i915"];
    kernelPackages = pkgs.linuxPackages_cachyos;
    supportedFilesystems = ["btrfs" "ntfs"];
    tmp.useTmpfs = true;

    initrd = {
      # Encrypted device
      luks.devices."enc".device = "/dev/disk/by-uuid/9952fcd1-46eb-4c9c-ab7d-361d31fdb9a2";

      systemd = {
        enable = true;
        emergencyAccess = true;
        dbus.enable = true;

        initrdBin = with pkgs; [
          iwd
          nix
          vim
        ];

        services.wipe-root = {
          requires = ["dev-mapper-enc.device"];
          after = ["dev-mapper-enc.device"];
          wantedBy = ["initrd.target"];
          script = lib.mkAfter ''
            mkdir /btrfs_tmp
            mount /dev/mapper/enc /btrfs_tmp
            if [[ -e /btrfs_tmp/root ]]; then
              mkdir -p /btrfs_tmp/old_roots
              timestamp=$(date --date="@$(stat -c %Y /btrfs_tmp/root)" "+%Y-%m-%-d_%H:%M:%S")
              mv /btrfs_tmp/root "/btrfs_tmp/old_roots/$timestamp"
            fi

            delete_subvolume_recursively() {
              IFS=$'\n'
              for i in $(btrfs subvolume list -o "$1" | cut -f 9- -d ' '); do
              delete_subvolume_recursively "/btrfs_tmp/$i"
              done
              btrfs subvolume delete "$1"
            }

            for i in $(find /btrfs_tmp/old_roots/ -maxdepth 1 -mtime +30); do
              delete_subvolume_recursively "$i"
            done

            btrfs subvolume create /btrfs_tmp/root
            umount /btrfs_tmp
          '';
        };
      };
    };

    extraModprobeConfig =
      "options nvidia "
      + lib.concatStringsSep " " [
        "NVreg_EnablePCIeGen3=1"
        "NVreg_RegistryDwords=RMUseSwI2c=0x01;RMI2cSpeed=100"
        "NVreg_UsePageAttributeTable=1"
      ];

    kernelParams = [
      "intel_iommu=on"
      "iommu=pt"
      "kvm.ignore_msrs=1"
      "modprobe.blacklist=nouveau,i915"
      "nvidia_drm.fbdev=1"
    ];

    loader = {
      efi.canTouchEfiVariables = true;

      systemd-boot = {
        enable = true;
        configurationLimit = 3;
      };
    };
  };

  nix = {
    daemonCPUSchedPolicy = "batch";
    daemonIOSchedClass = "idle";
    daemonIOSchedPriority = 7;

    gc = {
      automatic = true;
      dates = "Sat *-*-* 03:00";
      options = "--delete-older-than 30d";
    };

    optimise = {
      automatic = true;
      dates = ["04:00"];
    };

    settings = {
      auto-optimise-store = true;
      builders-use-substitutes = true;
      flake-registry = "/etc/nix/registry.json";
      keep-going = true;
      log-lines = 30;
      max-jobs = "auto";
      sandbox-fallback = false;
      sandbox = true;
      system-features = ["nixos-test" "kvm" "recursive-nix" "big-parallel" "gccarch-x86-64-v4"];
      use-cgroups = true;
      use-xdg-base-directories = true;
      warn-dirty = false;

      allowed-users = ["root" "@wheel" "nix-builder"];
      trusted-users = ["root" "@wheel" "nix-builder"];

      min-free = "${toString (5 * 1024 * 1024 * 1024)}";
      max-free = "${toString (10 * 1024 * 1024 * 1024)}";

      extra-experimental-features = [
        "flakes" # flakes
        "nix-command" # experimental nix commands
        "recursive-nix" # let nix invoke itself
        "ca-derivations" # content addressed nix
        "auto-allocate-uids" # allow nix to automatically pick UIDs, rather than creating nixbld* user accounts
        "cgroups" # allow nix to execute builds inside cgroups
      ];

      substituters = [
        "https://cache.nixos.org?priority=100"
        "https://cache.privatevoid.net"
        "https://cosmic.cachix.org/"
        "https://cuda-maintainers.cachix.org"
        "https://hyprland.cachix.org"
        "https://nix-community.cachix.org"
      ];

      trusted-public-keys = [
        "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="
        "cache.privatevoid.net:SErQ8bvNWANeAvtsOESUwVYr2VJynfuc9JRwlzTTkVg="
        "cosmic.cachix.org-1:Dya9IyXD4xdBehWjrkPv6rtxpmMdRel02smYzA85dPE="
        "cuda-maintainers.cachix.org-1:0dq3bujKpuEPMCX6U4WylrUDZ9JyUG0VpVZa7CNfq5E="
        "hyprland.cachix.org-1:a7pgxzMz7+chwVL3/pzj6jIBMioiJM7ypFP8PwtkuGc="
        "nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs="
      ];
    };
  };

  programs = {
    dconf.enable = true;
    fish.enable = true;
    gamemode.enable = true;
    steam.enable = true;
    gnupg.agent.enable = true;
    virt-manager.enable = true;

    appimage = {
      enable = true;
      binfmt = true;
    };

    hyprland = {
      enable = true;
      package = inputs.hyprland.packages.${pkgs.system}.hyprland;
    };

    nh = {
      enable = true;
      flake = "/home/marshall/nix-config";
    };

    obs-studio = {
      enable = true;
      enableVirtualCamera = true;
    };
  };

  networking = {
    firewall.enable = false;
    networkmanager.enable = true;
    hostName = "navis";
    nameservers = ["1.1.1.1" "1.0.0.1"];
    useDHCP = lib.mkForce true;
  };

  time = {
    hardwareClockInLocalTime = true;
    timeZone = "America/New_York";
  };

  services = {
    ddccontrol.enable = true;
    flatpak.enable = true;
    getty.autologinUser = "marshall";
    gnome.gnome-keyring.enable = true;
    mullvad-vpn.enable = true;
    openssh.enable = true;
    spice-vdagentd.enable = true;
    udisks2.enable = true;

    btrfs.autoScrub = {
      enable = true;
      fileSystems = ["/dev/mapper/enc"];
    };

    displayManager.cosmic-greeter.enable = true;
    desktopManager.cosmic.enable = true;

    libinput = {
      enable = true;
      touchpad.naturalScrolling = true;
    };

    xserver = {
      enable = true;
      videoDrivers = ["nvidia"];

      displayManager.startx.enable = true;

      windowManager.xmonad = {
        enable = false;
        enableContribAndExtras = true;
        enableConfiguredRecompile = true;
        flake = {
          enable = true;
          compiler = "ghc982";
        };
      };
    };

    pipewire = {
      enable = true;
      pulse.enable = true;

      alsa = {
        enable = true;
        support32Bit = true;
      };
    };
  };

  users = {
    mutableUsers = false;

    users.marshall = {
      hashedPasswordFile = config.age.secrets.passwd.path;
      isNormalUser = true;
      shell = pkgs.fish;

      extraGroups = [
        "disk"
        "gamemode"
        "libvirtd"
        "networkmanager"
        "qemu-libvirtd"
        "tss"
        "wheel"
      ];
    };
  };

  snowfallorg.users.marshall = {
    create = true;
    admin = true;
  };

  home-manager.useGlobalPkgs = true;

  hardware = {
    bluetooth.enable = true;
    i2c.enable = true;

    graphics = {
      enable = true;
      enable32Bit = true;
      extraPackages = with pkgs; [
        vaapiVdpau
        nvidia-vaapi-driver
      ];
    };

    nvidia-container-toolkit.enable = true;

    nvidia = {
      package = config.boot.kernelPackages.nvidiaPackages.beta;
      modesetting.enable = true;
      powerManagement.enable = false;
      open = true;
    };
  };

  xdg.portal = {
    enable = true;
    xdgOpenUsePortal = true;

    config.common.default = "*";

    extraPortals = [
      pkgs.xdg-desktop-portal-cosmic
      pkgs.xdg-desktop-portal-gnome
      pkgs.xdg-desktop-portal-gtk
    ];
  };

  system.stateVersion = "24.05";
}
