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

let
  cfg = config.system.vpns;
in
{
  options.system.vpns = {
    enable = lib.mkEnableOption "enables vpns";
  
    # toggle for pia mexico w/ openvpn
    openvpn_pia_mexico = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = "enable pia vpn to mexico using openvpn";
    };
     wg_mex = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = "enable pia vpn to mexico using wireguard";
    };
    
  };

  config = lib.mkIf cfg.enable {
    
    # enable pia mexico w/ openvpn
    services.openvpn.servers = lib.mkIf cfg.openvpn_pia_mexico { 
      openvpn_pia_mexico = {
        config = ''
          config ${config.sops.secrets."openvpn_pia_mexico_config".path}
          auth-user-pass ${config.sops.secrets."_pia_auth".path}
        '';
      };
    };

    # enable mullvad mexico w/ wireguard
    networking.wg-quick.interfaces = lib.mkIf cfg.wg_mex {
      wg_mex = {
        # client settings
        table = "51820";
        privateKeyFile = config.sops.secrets."wg_mex_key".path;
        address = [ "10.74.252.231/32" "fc00:bbbb:bbbb:bb01::b:fce6/128" ];
        dns = [ "10.64.0.1" ];
        # remote settings
        peers = [ {
            publicKey = "yxyntWsANEwxeR0pOPNAcfWY7zEVICZe9G+GxortzEY=";
            allowedIPs = [ "0.0.0.0/0" "::0/0" ];
            endpoint = "149.88.22.129:51820";
            persistentKeepalive = 25;
          } ];
#        postUp = ''
#          ip rule add fwmark 0xca6c table 51820
#          ip route add default dev wg_mex table 51820
#          ip route add 10.10.0.0/24 dev enp89s0 table 51820
#        '';
#
#        postDown = ''
#          ip rule delete fwmark 0xca6c table 51820
#          ip route flush table 51820
#
#        '';
      };
    };

    # secrets only if VPN is enabled
    sops.secrets = lib.mkIf cfg.enable {
      "wg_mex_key" = { owner = "root"; group = "root"; };
      "pia_auth" = { owner = "root"; group = "root"; };
      "openvpn_pia_mexico_config" = {owner = "root"; group = "root"; };
 
    };
  };
}
