{
  config,
  lib,
  pkgs,
  ...
}: let
  cfg = config.hive.wg.server;
  peers = import ./peers.nix {inherit lib;};
in {
  options.hive.wg.server = {
    enable = lib.mkEnableOption "Enable WireGuard server";
    port = lib.mkOption {
      type = lib.types.port;
      default = 51820;
      description = "Port for WireGuard server";
    };
    privateKeyFile = lib.mkOption {
      type = lib.types.path;
      description = "Path to the private key file for the WireGuard server";
    };
  };

  config = lib.mkIf cfg.enable {
    # Firewall rule
    networking.firewall.allowedUDPPorts = [cfg.port];

    # Interface without internet routing
    networking.wireguard.interfaces."wg0" = {
      ips = ["10.10.10.1/24"];
      listenPort = cfg.port;
      inherit (cfg) privateKeyFile;

      peers = peers.forServer;

      # Allow p2p traffic
      postSetup = ''
        ${pkgs.iptables}/bin/iptables -A FORWARD -i wg0 -o wg0 -j ACCEPT
      '';

      # Undo the above
      postShutdown = ''
        ${pkgs.iptables}/bin/iptables -D FORWARD -i wg0 -o wg0 -j ACCEPT
      '';
    };
  };
}
