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

{
  options.modules.nordvpn.enable = lib.mkEnableOption "Whether to enable the NordVPN daemon";

  config = lib.mkIf config.modules.nordvpn.enable (
    let
      nordVPN = pkgs.callPackage ../derivations/nordvpn.nix { inherit pkgs lib; };
      preScript = pkgs.writeShellScript "nordvpn-start" ''
        mkdir -m 700 -p /var/lib/nordvpn;
        if [ -z "$(ls -A /var/lib/nordvpn)" ]; then
          cp -r ${nordVPN}/var/lib/nordvpn/* /var/lib/nordvpn;
        fi
      '';
    in
    {
      networking.firewall.checkReversePath = false;
      networking.firewall.allowedUDPPorts = [ 1194 ];
      networking.firewall.allowedTCPPorts = [ 443 ];

      environment.systemPackages = [ nordVPN ];
      users.groups.nordvpn = { };

      systemd.services.nordvpn = {
        description = "NordVPN daemon.";
        serviceConfig = {
          ExecStart = "${nordVPN}/bin/nordvpnd";
          ExecStartPre = preScript;
          NonBlocking = true;
          KillMode = "process";
          Restart = "on-failure";
          RestartSec = 5;
          RuntimeDirectory = "nordvpn";
          RuntimeDirectoryMode = "0750";
          Group = "nordvpn";
        };
        wantedBy = [ "multi-user.target" ];
        after = [ "network-online.target" ];
        wants = [ "network-online.target" ];
      };
    }
  );
}
