{ flake, pkgs, customUtils, lib, config, path, ... }:
{
  imports = with flake.nixosModules.systemProfiles; [
    ./hw.nix
    ./mail
    initrd-all-crypto-modules default-locale openssh rebuild-machines
  ];

  config = {
    nixpkgs = {
      system = "x86_64-linux";
      config = {
        allowUnfree = true;
      };
    };

    boot = {
      initrd = {
        luks.devices = {
          nvm0.device = "/dev/disk/by-uuid/fe641e81-0812-4181-a5f6-382ebba509bb";
          nvm1.device = "/dev/disk/by-uuid/43df1ba8-1728-4193-8855-920a82d4494a";
        };
        availableKernelModules = [ "drbg" "nvme" "xhci_pci" "usb_storage" "sd_mod" "rtsx_pci_sdmmc" ];
        kernelModules = [ "dm-raid" "dm-integrity" "dm-snapshot" "dm-thin-pool" ];
      };

      blacklistedKernelModules = [ "nouveau" ];

      # Use the systemd-boot EFI boot loader.
      loader = {
        systemd-boot.enable = true;
        efi.canTouchEfiVariables = true;
        timeout = null;
      };

      plymouth.enable = true;

      kernelPackages = pkgs.linuxPackages_latest;
      kernelParams = [ "i915.fastboot=1" "intel_pstate=no_hwp" "acpi_backlight=vendor" "thinkpad-acpi.brightness_enable=1" "quiet" ];
      extraModulePackages = with config.boot.kernelPackages; [ v4l2loopback ];
      kernelModules = ["v4l2loopback"];

      tmpOnTmpfs = true;
    };

    networking = {
      domain = "yggdrasil";
      search = [ "yggdrasil" ];
      hosts = {
        "127.0.0.1" = [ "sif.yggdrasil" "sif" ];
        "::1" = [ "sif.yggdrasil" "sif" ];
      };

      firewall = {
        enable = true;
        allowedTCPPorts = [ 22 # ssh
                            8000 # quickserve
                          ];
      };

      networkmanager = {
        enable = true;
        dhcp = "internal";
        dns = lib.mkForce "dnsmasq";
        extraConfig = ''
          [connectivity]
          uri=https://online.yggdrasil.li
        '';
      };

      # wlanInterfaces = {
      #   wlan0 = {
      #     device = "wlp82s0";
      #   };
      # };

      # bonds = {
      #   "lan" = {
      #     interfaces = [ "wlan0" "enp0s31f6" "dock0" ];
      #     driverOptions = {
      #       miimon = "1000";
      #       mode = "active-backup";
      #       primary_reselect = "always";
      #     };
      #   };
      # };

      dhcpcd.enable = false;
      useDHCP = false;
      useNetworkd = true;

      # interfaces."tinc.yggdrasil" = {
      #   virtual = true;
      #   virtualType = config.services.tinc.networks.yggdrasil.interfaceType;
      #   macAddress = "5c:93:21:c3:61:39";
      # };
    };

    systemd.services."NetworkManager-wait-online".enable = false;
    systemd.services."systemd-networkd-wait-online".enable = false;

    environment.etc."NetworkManager/dnsmasq.d/libvirtd_dnsmasq.conf" = {
      text = ''
        server=/sif.libvirt/192.168.122.1
      '';
    };

    services.openssh.enable = true;

    powerManagement = {
      enable = true;

      cpuFreqGovernor = "schedutil";
    };

    environment.systemPackages = with pkgs; [
      nvtop brightnessctl config.boot.kernelPackages.v4l2loopback s-tui uhk-agent
    ];

    services = {
      udev.packages = with pkgs; [ uhk-agent ];
      
      # tinc.yggdrasil.enable = true;

      uucp = {
        enable = true;
        nodeName = "sif";
        remoteNodes = {
          "ymir" = {
            publicKeys = ["ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG6KNtsCOl5fsZ4rV7udTulGMphJweLBoKapzerWNoLY root@ymir"];
            hostnames = ["ymir.yggdrasil.li" "ymir.niflheim.yggdrasil"];
          };
        };

        defaultCommands = lib.mkForce [];
      };

      avahi.enable = true;

      fwupd.enable = true;

      fprintd.enable = true;

      blueman.enable = true;
    
      colord.enable = true;
    
      vnstat.enable = true;

      logind = {
        lidSwitch = "suspend";
        lidSwitchDocked = "lock";
        lidSwitchExternalPower = "lock";
      };

      atd = {
        enable = true;
        allowEveryone = true;
      };

      xserver = {
        enable = true;

        layout = "us";
        xkbVariant = "dvp";
        xkbOptions = "compose:caps";

        displayManager.lightdm = {
          enable = true;
          greeters.gtk = {
            clock-format = "%H:%M %a %b %_d";
            indicators = ["~host" "~spacer" "~clock" "~session" "~power"];
            theme = {
              package = pkgs.equilux-theme;
              name = "Equilux-compact";
            };
            iconTheme = {
              package = pkgs.paper-icon-theme;
              name = "Paper";
            };
            extraConfig = ''
              background = #000000
              user-background = false
              active-monitor = #cursor
              hide-user-image = true

              [monitor: DP-2]
                laptop = true
            '';
          };
        };

        displayManager.setupCommands = ''
          ${pkgs.xorg.xinput}/bin/xinput disable 'SynPS/2 Synaptics TouchPad'
        '';

        desktopManager.xterm.enable = true;
        windowManager.twm.enable = true;
        displayManager.defaultSession = "xterm+twm";

        wacom.enable = true;
        libinput.enable = true;

        dpi = 282;

        videoDrivers = [ "nvidia" ];

        screenSection = ''
          Option "metamodes" "nvidia-auto-select +0+0 { ForceCompositionPipeline = On }"
        '';

        deviceSection = ''
          Option "AccelMethod" "SNA"
          Option "TearFree" "True"
        '';

        exportConfiguration = true;
      };
    };

    users = {
      users.gkleen.extraGroups = [ "media" "plugdev" ];
      groups.media = {};
      groups.plugdev = {};
    };

    hardware = {
      pulseaudio = {
        enable = true;
        package = with pkgs; pulseaudioFull;
        support32Bit = true;
      };

      bluetooth = {
        enable = true;   
        settings = {
          General = {
            Enable = "Source,Sink,Media,Socket";
          };
        };
      };

      trackpoint = {
        enable = true;
        emulateWheel = true;
        sensitivity = 255;
        speed = 255;
      };

      nvidia = {
        modesetting.enable = true;
        prime = {
          nvidiaBusId = "PCI:1:0:0";
          intelBusId = "PCI:0:2:0";
          sync.enable = true;
        };
      };

      opengl = {
        enable = true;
        driSupport32Bit = true;
        setLdLibraryPath = true;
      };

      firmware = [ pkgs.firmwareLinuxNonfree ];
    };

    sound.enable = true;

    nix = {
      autoOptimiseStore = true;
      daemonNiceLevel = 10;
      daemonIONiceLevel = 3;

      buildServers.vidhar = {
        address = "vidhar.yggdrasil";
        systems = ["x86_64-linux" "i686-linux"];
        maxJobs = 12;
        speedFactor = 4;
        supportedFeatures = ["nixos-test" "benchmark" "big-parallel" "kvm"];
      };
    };

    environment.etc."X11/xorg.conf.d/50-wacom.conf".source = lib.mkForce ./wacom.conf;

    systemd.services."ac-plugged" = {
      description = "Inhibit handling of lid-switch and sleep";

      path = with pkgs; [ systemd coreutils ];

      script = ''
        exec systemd-inhibit --what=handle-lid-switch --why="AC is connected" --mode=block sleep infinity
      '';

      serviceConfig = {
        Type = "simple";
      };
    };

    services.udev.extraRules = with pkgs; lib.mkAfter ''
      SUBSYSTEM=="power_supply", ENV{POWER_SUPPLY_ONLINE}=="0", RUN+="${systemd}/bin/systemctl --no-block stop ac-plugged.service"
      SUBSYSTEM=="power_supply", ENV{POWER_SUPPLY_ONLINE}=="1", RUN+="${systemd}/bin/systemctl --no-block start ac-plugged.service"
      ACTION=="add", SUBSYSTEM=="net", DEVTYPE!="?*", ATTR{address}=="3c:e1:a1:b9:cd:e5", NAME="dock0"
    '';

    services.borgbackup = {
      snapshots = "btrfs";
      prefix = "yggdrasil.midgard.sif.";
      targets = {
        "munin" = {
          repo = "borg.munin:borg";
          paths = [ "/home/gkleen" ];
          prune = {
            "home" =
              [ "--keep-within" "24H"
                "--keep-daily" "31"
                "--keep-monthly" "12"
                "--keep-yearly" "-1"
              ];
          };
          keyFile = "/run/secrets/borg-repokey--borg_munin__borg";
        };
      };
    };
    sops.secrets.borg-repokey--borg_munin__borg = {
      sopsFile = /. + path + "/modules/borgbackup/repokeys/borg_munin__borg.yaml";
      key = "key";
    };

    services.btrfs.autoScrub = {
      enable = true;
      fileSystems = [ "/" "/home" ];
      interval = "weekly";
    };

    systemd.services."nix-daemon".serviceConfig = {
      MemoryAccounting = true;
      MemoryHigh = "50%";
      MemoryMax = "75%";
    };

    services.journald.extraConfig = ''
      SystemMaxUse=100M
    '';

    services.dbus.packages = with pkgs;
      [ dbus gnome3.dconf
      ];

    programs = {
      light.enable = true;
      wireshark.enable = true;
      dconf.enable = true;
    };

    virtualisation.libvirtd = {
      enable = true;
    };

    zramSwap.enable = true;

    services.pcscd.enable = true;

    system.stateVersion = "20.03";
  };
}