{ config, pkgs, ... }:

let
  tatosData = import ../../tatos/data.secret.nix;

  istalData = import ../data.secret.nix;
  inherit (istalData.wireguard) port;
in
{
  boot.kernel.sysctl."net.ipv4.ip_forward" = 1;
  boot.kernel.sysctl."net.ipv4.conf.all.forwarding" = 1;

  # enable NAT
  networking.nat = {
    enable = true;
    externalInterface = "enp0s5";
    internalInterfaces = [ "wg0" ];
  };

  networking.wg-quick.interfaces = {
    # "wg0" is the network interface name. You can name the interface arbitrarily.
    wg0 = {
      # Determines the IP address and subnet of the server's end of the tunnel interface.
      address = [ "10.20.30.2/32" ];

      # The port that WireGuard listens to. Must be accessible by the client.
      listenPort = port;

      # 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
      postUp = ''
        ${pkgs.iptables}/bin/iptables -t nat -A POSTROUTING -o enp0s5 -j MASQUERADE
      '';

      # This undoes the above command
      preDown = ''
        ${pkgs.iptables}/bin/iptables -t nat -D POSTROUTING -o enp0s5 -j MASQUERADE
      '';

      # Path to the private key file.
      privateKeyFile = config.age.secrets.wireguard-istal-private.path;

      peers = [
        {
          publicKey = tatosData.wireguard.publicKey;
          allowedIPs = [ "10.20.30.0/24" ];
          endpoint = "${tatosData.addr}:${toString tatosData.wireguard.port}";
          persistentKeepalive = 25;
        }
      ];
    };
  };

  age.secrets.wireguard-istal-private = {
    file = ../../../../secrets/wireguard-istal-private.age;
    mode = "0400";
  };
}
