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

with lib;

let cfg = config.hacc.encboot;

in {
  options = {
    hacc.encboot = {
      enable = mkOption {
        type = types.bool;
        default = false;
      };
      networkDrivers = mkOption { type = with types; listOf str; };
      dataset = mkOption {
        type = types.str;
        default = "zroot";
      };
    };
  };

  config = mkIf cfg.enable {
    boot.initrd.kernelModules = cfg.networkDrivers;

    boot.initrd.network = {
      enable = true;
      ssh = {
        enable = true;
        port = 2222;
        authorizedKeys = with lib;
          concatLists (mapAttrsToList (name: user:
            if elem "wheel" user.extraGroups then
              user.openssh.authorizedKeys.keys
            else
              [ ]) config.users.users);
        hostKeys = [ /etc/ssh/encboot_host ];
      };

      postCommands = ''
        zpool import ${cfg.dataset}
        echo "zfs load-key -a; killall zfs && exit" >> /root/.profile
      '';
    };
  };
}