{
  config,
  pkgs,
  lib,
  project-cloud,
  nvim,
  system,
  ...
}: {
  imports = [];

  nix.optimise.automatic = true;
  nix.settings.experimental-features = ["nix-command" "flakes"];
  system.switch = {
    enable = false;
    enableNg = true;
  };

  # Use the systemd-boot EFI boot loader.
  boot.loader.systemd-boot.enable = true;
  boot.loader.systemd-boot.configurationLimit = 2;
  boot.loader.efi.canTouchEfiVariables = true;
  boot.kernelPackages = pkgs.linuxPackages_latest;
  boot.kernelParams = ["ip=dhcp" "console=tty"];
  boot.kernel.sysctl = {
    "net.core.default_qdisc" = "fq";
    "net.ipv4.tcp_congestion_control" = "bbr";
  };

  boot.initrd = {
    compressor = "zstd";
    availableKernelModules = ["virtio-pci"];
    systemd.enable = true;
    network = {
      enable = true;
      ssh = {
        enable = true;
        hostKeys = [/etc/ssh_dummy_ed25519_key];
        authorizedKeyFiles = [../nixy/ssh_pubkey];
      };
    };
  };

  # Set your time zone.
  time.timeZone = "Europe/Berlin";

  users.users.root.initialHashedPassword = "";
  users.users.root.openssh.authorizedKeys.keys = [
    (builtins.readFile ../nixy/ssh_pubkey)
  ];

  environment.systemPackages = with pkgs; [
    curl
    fd
    file
    fzf
    fzy
    git
    nvim.packages.${system}.nvim
    htop-vim
    nvim
    pciutils
    tig
    tmux
    unzip
    usbutils
    wget
    zip
  ];

  programs.mosh.enable = true;

  mailserver = {
    enable = true;
    debug = false;
    fqdn = "mail.project-cloud.net";
    domains = ["project-cloud.net"];
    enableSubmissionSsl = true;
    enableImap = false;
    enableImapSsl = true;

    # A list of all login accounts. To create the password hashes, use
    # nix-shell -p mkpasswd --run 'mkpasswd -sm bcrypt'
    loginAccounts = {
      "gitea@project-cloud.net" = {
        hashedPasswordFile = config.sops.secrets."gitea_mail_pw_hash".path;
        aliases = ["git@project-cloud.net"];
      };
      "asmir@project-cloud.net" = {
        hashedPasswordFile = config.sops.secrets."asmir_mail_pw_hash".path;
        aliases = ["asmir.abdulahovic@project-cloud.net"];
      };
    };
    certificateScheme = "acme-nginx";
  };

  services.journald.extraConfig = ''SystemMaxUse=50M '';
  services.logind.extraConfig = ''KillUserProcesses=yes '';
  services.openssh.settings.PermitRootLogin = "prohibit-password";
  services.openssh.enable = true;
  services.openssh.listenAddresses = [
    {
      addr = "10.100.0.1"; # wireguard
      port = 22;
    }
  ];
  services.opendkim.enable = true;

  services.miniflux = {
    enable = false;
    adminCredentialsFile = config.sops.secrets."miniflux_env".path;
    config = {
      LISTEN_ADDR = "localhost:5001";
      BASE_URL = "https://miniflux.project-cloud.net";
    };
  };

  services.goatcounter = {
    enable = true;
    port = 8002;
    proxy = true;
    address = "127.0.0.1";
  };

  services.nextcloud = {
    enable = false;
    package = pkgs.nextcloud28;
    config.adminpassFile = config.sops.secrets."nextcloud_admin".path;
    configureRedis = true;
    hostName = "cloud.project-cloud.net";
    https = true;
    settings = {
      mail_smtpmode = "sendmail";
      mail_sendmailmode = "pipe";
      enabledPreviewProviders = [
        "OC\\Preview\\BMP"
        "OC\\Preview\\GIF"
        "OC\\Preview\\HEIC"
        "OC\\Preview\\JPEG"
        "OC\\Preview\\Krita"
        "OC\\Preview\\MarkDown"
        "OC\\Preview\\MP3"
        "OC\\Preview\\OpenDocument"
        "OC\\Preview\\PNG"
        "OC\\Preview\\TXT"
        "OC\\Preview\\XBitmap"
      ];
    };
    phpOptions = {
      "opcache.jit" = "tracing";
      "opcache.jit_buffer_size" = "100M";
      "opcache.interned_strings_buffer" = "16";
    };
  };

  services.nginx = {
    enable = true;
    package = pkgs.nginxQuic;
    recommendedGzipSettings = true;
    recommendedOptimisation = true;
    recommendedProxySettings = true;
    recommendedTlsSettings = true;

    virtualHosts."project-cloud.net" = {
      quic = true;
      http3 = true;
      forceSSL = true;
      enableACME = true;
      root = "${project-cloud.packages.${system}.default}/public";
    };

    /*
    virtualHosts.${config.services.nextcloud.hostName} = {
      quic = true;
      http3 = true;
      forceSSL = true;
      enableACME = true;
    };
    */

    virtualHosts."miniflux.project-cloud.net" = {
      quic = true;
      http3 = true;
      forceSSL = true;
      enableACME = true;
      locations."/" = {
        proxyPass = "http://localhost:5001";
      };
    };

    virtualHosts.${config.services.gitea.settings.server.DOMAIN} = {
      quic = true;
      http3 = true;
      forceSSL = true;
      enableACME = true;
      locations."/" = {
        proxyPass = "http://unix:${toString config.services.gitea.settings.server.HTTP_ADDR}";
      };
    };

    virtualHosts."stats.project-cloud.net" = {
      quic = true;
      http3 = true;
      forceSSL = true;
      enableACME = true;
      locations."/" = {
        proxyPass = "http://localhost:8002/";
      };
    };
  };

  services.gitea = {
    enable = true;
    appName = "Project Cloud Gitea server";
    database = {
      type = "sqlite3";
      passwordFile = config.sops.secrets."gitea_db".path;
    };
    settings.server = {
      DOMAIN = "git.project-cloud.net";
      ROOT_URL = "https://git.project-cloud.net";
      DISABLE_SSH = true;
      HTTP_PORT = 3001;
      LANDING_PAGE = "explore";
      PROTOCOL = "http+unix";
    };
    settings.mailer = {
      ENABLED = true;
      FROM = "gitea@project-cloud.net";
      PROTOCOL = "sendmail";
      SENDMAIL_PATH = "/run/wrappers/bin/sendmail";
    };

    settings.service = {
      DISABLE_REGISTRATION = true;
      REGISTER_EMAIL_CONFIRM = true;
    };

    settings."markup.restructuredtext" = let
      docutils =
        pkgs.python3.withPackages (ps: with ps; [docutils pygments]);
    in {
      ENABLED = true;
      FILE_EXTENSIONS = ".rst";
      RENDER_COMMAND = "${docutils}/bin/rst2html.py";
      IS_INPUT_FILE = false;
    };
  };

  services.nfs.server.enable = false;
  services.nfs.server.extraNfsdConfig = ''
    rdma = true
    vers3 = false
    vers4.0 = false
    vers4.1 = false
  '';
  services.nfs.server.exports = ''
    /export/nixy    10.100.0.1/24(rw,nohide,insecure,no_subtree_check,all_squash,anonuid=1000,anongid=100)
  '';

  services.borgbackup.jobs."borgbase" = {
    paths = [
      "/var/lib/gitea"
    ];
    exclude = [];
    repo = "ssh://na9fqv67@na9fqv67.repo.borgbase.com/./repo";
    encryption = {
      mode = "repokey-blake2";
      passCommand = "${pkgs.coreutils-full}/bin/cat ${config.sops.secrets."borgbase_enc_key".path}";
    };
    environment.BORG_RSH = "${pkgs.openssh}/bin/ssh -i ${config.sops.secrets."borgbase_ssh_key".path}";
    compression = "auto,zstd";
    startAt = "daily";
  };

  services.seafile = {
    enable = false;
    initialAdminPassword = "admin";
    adminEmail = "asmir.abdulahovic" + "@" + "gmail.com";
  };

  /*
  needed for sendmail mail functionality
  */
  users.users.gitea.extraGroups = ["postdrop"];
  systemd.services.gitea.serviceConfig = {
    RestrictAddressFamilies = ["AF_NETLINK"];
    ProtectSystem = lib.mkForce false;
  };

  security.acme = {
    acceptTerms = true;
    defaults.email = "asmir.abdulahovic@gmail.com";
  };

  sops = {
    age.sshKeyPaths = ["/etc/ssh/ssh_host_ed25519_key"];
    secrets = {
      "asmir_mail_pw_hash".sopsFile = ./secrets/asmir_mail_pw_hash.yaml;
      "borgbase_enc_key".sopsFile = ./secrets/borgbase_enc_key.yaml;
      "borgbase_ssh_key".sopsFile = ./secrets/borgbase_ssh_key.yaml;
      "gitea_mail_pw_hash".sopsFile = ./secrets/gitea_mail_pw_hash.yaml;
      "miniflux_env".sopsFile = ./secrets/miniflux.yaml;
      "wg_preshared/mediabox".sopsFile = ../common/secrets/wg_preshared.yaml;
      "wg_preshared/nixy".sopsFile = ../common/secrets/wg_preshared.yaml;
      "wg_preshared/workstation".sopsFile = ../common/secrets/wg_preshared.yaml;
      "wg_privkey".sopsFile = ./secrets/wg_privkey.yaml;
      "gitea_db" = {
        sopsFile = ./secrets/gitea_db.yaml;
        owner = config.users.users.gitea.name;
      };
      /*
      "nextcloud_admin" = {
        sopsFile = ./secrets/nextcloud_admin.yaml;
        owner = config.users.users.nextcloud.name;
      };
      */
    };
  };

  networking.hostName = "magpie";

  networking.firewall.enable = true;
  networking.firewall.allowedTCPPorts = [80 443 587 2049]; # http, mail, mail, nfs
  networking.firewall.allowedUDPPorts = [443 51820]; #mail, wireguard
  networking.firewall.allowPing = true;
  networking.firewall.logRefusedConnections = lib.mkDefault false;

  networking.nat.enable = true;
  networking.nat.externalInterface = "enp1s0";
  networking.nat.internalInterfaces = ["wg0"];

  networking.networkmanager.enable = true;
  networking.wireless.enable = false;

  networking.wireguard.interfaces = {
    wg0 = {
      ips = ["10.100.0.1/24"];
      listenPort = 51820;

      # This allows the wireguard server to route your traffic to the internet and hence be like a VPN
      # For this to work you have to set the dnsserver IP of your router (or dnsserver of choice) in your clients
      postSetup = ''
        ${pkgs.iptables}/bin/iptables -t nat -A POSTROUTING -s 10.100.0.0/24 -o eth0 -j MASQUERADE
      '';
      # This undoes the above command
      postShutdown = ''
        ${pkgs.iptables}/bin/iptables -t nat -D POSTROUTING -s 10.100.0.0/24 -o eth0 -j MASQUERADE
      '';
      privateKeyFile = config.sops.secrets."wg_privkey".path;

      peers = [
        {
          publicKey = builtins.readFile ../nixy/wg_pubkey;
          presharedKeyFile = config.sops.secrets."wg_preshared/nixy".path;
          allowedIPs = ["10.100.0.6/32"];
        }
        {
          publicKey = builtins.readFile ../mediabox/wg_pubkey;
          presharedKeyFile = config.sops.secrets."wg_preshared/mediabox".path;
          allowedIPs = ["10.100.0.5/32"];
        }
        {
          publicKey = builtins.readFile ../common/wg_pubkey_workstation;
          presharedKeyFile = config.sops.secrets."wg_preshared/workstation".path;
          allowedIPs = ["10.100.0.4/32"];
        }
      ];
    };
  };

  systemd = {
    enableEmergencyMode = false;

    watchdog = {
      runtimeTime = "20s";
      rebootTime = "30s";
    };

    sleep.extraConfig = ''
      AllowSuspend=no
      AllowHibernation=no
    '';
  };

  system.stateVersion = "22.11";
}