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

let password = builtins.readFile /var/keys/ddclient;

in {
  # Assign a static IP
  networking = {
    hostName = "unit";
    hostId = "737d82f4";
    interfaces.eth0 = {
      useDHCP = false;
      ipv4.addresses = [{
        address = "10.0.1.3";
        prefixLength = 24;
      }];
    };
    defaultGateway = {
      address = "10.0.1.1";
      interface = "eth0";
    };
    nameservers = [ "1.1.1.1" "8.8.8.8" ];
    enableIPv6 = false;
  };

  # Enable zeroconf
  services.avahi = {
    enable = true;
    nssmdns = true;
    publish = {
      enable = true;
      addresses = true;
      domain = true;
    };
  };

  # Dynamic DNS configuration
  services.ddclient = {
    enable = true;
    quiet = true;
    protocol = "duckdns";
    domains = [ "coace.duckdns.org" ];
    inherit password;
  };

  # Firewall configuration
  networking.firewall = {
    allowedTCPPorts = [
      445 # Samba
      139 # Samba
      2222 # VM SSH
      5000 # Sybase
      80 # HTTP
      443 # HTTPS
    ];
    allowedUDPPorts = [
      137 # Samba
      138 # Samba
      1194 # Wireguard
    ];
    allowPing = true;
  };

  # Enable NAT for wireguard and forward ports to sica VM
  networking.nat = {
    enable = true;
    externalInterface = "eth0";
    internalInterfaces = [ "wg0" "br0" ];
    forwardPorts = [
      {
        destination = "192.168.122.100:22";
        sourcePort = 2222;
        loopbackIPs = [ "10.0.1.3" ];
      }
      {
        destination = "192.168.122.100:5000";
        sourcePort = 5000;
        loopbackIPs = [ "10.0.1.3" ];
      }
    ];
  };

  # Wireguard setup
  networking.wireguard.interfaces = {
    wg0 = {
      ips = [ "10.9.0.1/24" ];
      listenPort = 1194;
      privateKeyFile = "/home/coace/.wg/server/privatekey";
      peers = [
        # panacea
        {
          publicKey = "XMkTztU2Y8hw6Fu/2o4Gszij+EmNacvFMXuZyHS1n38=";
          allowedIPs = [ "10.9.0.2/32" ];
        }
        # caravanserai
        {
          publicKey = "4jiEKaPjNPU3JghfwLyArRhCKZmT8VYN07iw0SL/eHc=";
          allowedIPs = [ "10.9.0.3/32" ];
        }
        # fernando
        {
          publicKey = "5DU9ipxJcut2wKrUr3yQux9crzXMSW4ZeKWFLRpUc1I=";
          allowedIPs = [ "10.9.0.4/32" ];
        }
      ];
    };
  };

  # QEMU virtual bridge
  networking.interfaces.br0 = {
    ipv4.addresses = [{
      address = "192.168.122.1";
      prefixLength = 24;
    }];
  };
  networking.bridges.br0.interfaces = [ ];

  services.dhcpd4 = {
    enable = true;
    interfaces = [ "br0" ];
    extraConfig = ''
      option routers 192.168.122.1;
      option broadcast-address 192.168.122.255;
      option subnet-mask 255.255.255.0;
      option domain-name-servers 1.1.1.1, 8.8.8.8;
      default-lease-time -1;
      max-lease-time -1;
      subnet 192.168.122.0 netmask 255.255.255.0 {
        range 192.168.122.100 192.168.122.200;
      }
    '';
  };

}