{ flake, pkgs, customUtils, lib, config, path, ... }:
let
  mwnSubnetsPublic =
    [ "129.187.0.0/16" "141.40.0.0/16" "141.84.0.0/16"
      "192.68.211.0/24" "192.68.212.0/24" "192.68.213.0/24" "192.68.214.0/24" "192.68.215.0/24"
      "193.174.96.0/22"
      "194.95.59.0/24"
    ];
  mwnSubnetsPrivate =
    [ "10.153.0.0/16" "10.162.0.0/16" "10.156.0.0/16"
    ];
in {
  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
      '';
    };
    environment.etc."NetworkManager/dnsmasq.d/wgrz.conf" = {
      text = ''
        server=/mathinst.loc/10.153.88.9
        server=/cipmath.loc/10.153.88.9
      '';
    };

    environment.etc."systemd/networkd.conf" = {
      text = ''
        [Network]
        RouteTable=wgrz:1025
      '';
    };
    systemd.network = {
      netdevs = {
        wgrz = {
          netdevConfig = {
            Name = "wgrz";
            Kind = "wireguard";
          };
          wireguardConfig = {
            PrivateKeyFile = config.sops.secrets.wgrz.path;
            ListenPort = 51822;
            # FirewallMark = 1;
          };
          wireguardPeers = [
            { wireguardPeerConfig = {
                AllowedIPs = [ "10.200.116.1/32" ] ++ mwnSubnetsPrivate ++ mwnSubnetsPublic;
                PublicKey = "YlRFLc+rD2k2KXl7pIJbOKbcPgdJCl8ZTsv0xlK4VEI=";
                PersistentKeepalive = 25;
                Endpoint = "wg.math.lmu.de:51820";
              };
            }
          ];
        };
      };
      networks = {
        wgrz = {
          name = "wgrz";
          matchConfig = {
            Name = "wgrz";
          };
          address = ["10.200.116.128/24"];
          routes = map (Destination: { routeConfig = {
            inherit Destination;
            Gateway = "10.200.116.1";
            GatewayOnLink = true;
            Table = "wgrz";
          };}) (mwnSubnetsPrivate ++ mwnSubnetsPublic);
          routingPolicyRules = [
            { routingPolicyRuleConfig = {
                Table = "main";
                # FirewallMark = 1;
                To = "129.187.111.225";
                Priority = 100;
              };
            }
            { routingPolicyRuleConfig = {
                Table = "wgrz";
                From = "10.200.116.128";
                Priority = 200;
              };
            }
          ] ++ map (To: { routingPolicyRuleConfig = {
                            Table = "wgrz";
                            inherit To;
                            Priority = 200;
                          };}) (mwnSubnetsPrivate ++ mwnSubnetsPublic);
          linkConfig = {
            RequiredForOnline = false;
          };
          networkConfig = {
            LLMNR = false;
            MulticastDNS = false;
            DNS = ["10.153.88.9" "129.187.111.202" "10.156.33.53"];
          };
        };
      };
    };
    sops.secrets.wgrz = {
      format = "binary";
      sopsFile = ./wgrz/privkey;
      mode = "0640";
      owner = "root";
      group = "systemd-network";
    };
    networking.networkmanager.unmanaged = ["wgrz"];

    services.resolved.enable = false;

    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;

      upower.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 = {};
    };

    security.rtkit.enable = true;
    services.pipewire = {
      enable = true;
      alsa.enable = true;
      alsa.support32Bit = true;
      pulse.enable = true;
      jack.enable = true;
      media-session.enable = false;
      wireplumber.enable = true;
    };

    hardware = {
      bluetooth = {
        enable = true;   
        package = pkgs.bluezFull;
        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 = {
      settings.auto-optimise-store = true;
      daemonCPUSchedPolicy = "idle";
      daemonIOSchedClass = "idle";

      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", KERNEL=="virbr0", ENV{NM_UNMANAGED}="1"
    '';

    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 dconf
      ];

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

    virtualisation.libvirtd = {
      enable = true;
    };

    zramSwap.enable = true;

    services.pcscd.enable = true;

    sops.secrets.gkleen-rclone = {
      sopsFile = ./gkleen-rclone.yaml;
      key = "passphrase";
      owner = "gkleen";
      group = "users";
    };

    system.stateVersion = "20.03";
  };
}