# Client section of our Monitoring VPN config

{ lib, config, ... }: let
  cfg = config.services.private-storage.monitoring.vpn;

in {
  options.services.private-storage.monitoring.vpn.client = {
    enable = lib.mkEnableOption "PrivateStorageio Monitoring VPN client service";
    privateKeyFile = lib.mkOption {
      type = lib.types.path;
      example = /run/keys/monitoringvpn/host.key;
      default = /run/keys/monitoringvpn/client.key;
      description = ''
        File with base64 private key generated by <command>wg genkey</command>.
        Shorthand to create private and public key:
        <command>wg genkey | tee peer_A.key | wg pubkey > peer_A.pub</command>
      '';
    };
    presharedKeyFile = lib.mkOption {
      type = lib.types.path;
      example = /run/keys/monitoringvpn/preshared.key;
      default = /run/keys/monitoringvpn/preshared.key;
      description = ''
        File with base64 preshared key generated by <command>wg genpsk</command>.
      '';
    };
    allowedIPs = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      example = [ "172.23.23.1/32" ];
      default = [ "172.23.23.1/32" ];
      description = ''
        Limits which IPs this client receives data from.
      '';
    };
    ip = lib.mkOption {
      type = lib.types.str;
      example = "172.23.23.11";
      description = ''
        The IP addresses of the interface.
      '';
    };
    endpoint = lib.mkOption {
      type = lib.types.str;
      example = "vpn.monitoring.private.storage:54321";
      description = ''
        The address and port number of the server to establish the VPN with.
      '';
    };
    endpointPublicKeyFile = lib.mkOption {
      type = lib.types.path;
      example = ./monitoringvpn/server.pub;
      description = ''
        File with base64 public key generated by <command>cat private.key | wg pubkey > pubkey.pub</command>.
      '';
    };
  };

  config = lib.mkIf cfg.client.enable {
    networking.wireguard.interfaces.monitoringvpn = {
      ips = [ "${cfg.client.ip}/24" ];
      privateKeyFile = toString cfg.client.privateKeyFile;
      peers = [
        {
          allowedIPs = cfg.client.allowedIPs;
          endpoint = cfg.client.endpoint;  # meaning: the server.
          publicKey = lib.fileContents(cfg.client.endpointPublicKeyFile);
          presharedKeyFile = toString cfg.client.presharedKeyFile;
          persistentKeepalive = 25;
        }
      ];
    };
  };
}