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

with lib;

let
  cfg = config.services.wg-clerie;
in

{
  options = {
    services.wg-clerie = {
      enable = mkEnableOption "VPN for public static IP";
      privateKeyFile = mkOption {
        type = with types; nullOr str;
        default = null;
        description = "Path to file containing private key for wireguard interface";
      };
      ipv6s = mkOption {
        type = with types; listOf str;
        default = [];
        description = "IPv6 interface addresses";
      };
      ipv4s = mkOption {
        type = with types; listOf str;
        default = [];
        description = "IPv4 interface addresses";
      };
      defaultViaVPN = mkOption {
        type = types.bool;
        default = true;
        description = "Use VPN default route for a protocol, if that protocol is unavailable in the underlay";
      };
    };
  };

  config = mkIf cfg.enable {
    networking.iproute2.enable = true;
    networking.iproute2.rttablesExtraConfig = ''
      200 wg-clerie
    '';

    petabyte.policyrouting = {
      enable = true;
      rules6 = (concatMap (ip: [
        { rule = "from ${ip} lookup wg-clerie"; prio = 19000; }
        { rule = "from ${ip} unreachable"; prio = 19001; }
      ]) cfg.ipv6s) ++ [
        # Do not reach VPN server via VPN
        { rule = "to 2a01:4f8:c0c:15f1::1/128 ipproto udp dport 51820 lookup main"; prio = 20000; }
        { rule = "to 2a01:4f8:c0c:15f1::1/128 ipproto udp dport 51820 unreachable"; prio = 20001; }
        # Try direct routing first, fallback to VPN
        { rule = "lookup main"; prio = 21000; }
      ] ++ (if cfg.defaultViaVPN then [
        { rule = "lookup wg-clerie"; prio = 21001; }
      ] else []) ++ [
        { rule = "unreachable"; prio = 22000; }
      ];
      rules4 = (concatMap (ip: [
        { rule = "from ${ip} lookup wg-clerie"; prio = 19000; }
        { rule = "from ${ip} unreachable"; prio = 19001; }
      ]) cfg.ipv4s) ++ [
        # Do not reach VPN server via VPN
        { rule = "to 78.47.183.82/32 ipproto udp dport 51820 lookup main"; prio = 20000; }
        { rule = "to 78.47.183.82/32 ipproto udp dport 51820 unreachable"; prio = 20001; }
        # Try direct routing first, fallback to VPN
        { rule = "lookup main"; prio = 21000; }
      ] ++ (if cfg.defaultViaVPN then [
        { rule = "lookup wg-clerie"; prio = 21001; }
      ] else []) ++ [
        { rule = "unreachable"; prio = 22000; }
      ];
    };

    networking.wireguard.enable = true;
    networking.wireguard.interfaces = {
      wg-clerie = {
        privateKeyFile = if cfg.privateKeyFile != null then cfg.privateKeyFile else
          config.sops.secrets.wg-clerie.path;
        ips = cfg.ipv6s ++ cfg.ipv4s;
        table = "wg-clerie";
        peers = [
          {
            # Fallback to legacy IP if there is no route to VPN server
            endpoint = "$(ip route get 2a01:4f8:c0c:15f1::1 ipproto udp dport 51820 &>/dev/null && echo '[2a01:4f8:c0c:15f1::1]:51820' || echo '78.47.183.82:51820')";
            persistentKeepalive = 25;
            dynamicEndpointRefreshSeconds = 5;
            allowedIPs = [ "0.0.0.0/0" "::/0" "10.20.30.0/24" "2a01:4f8:c0c:15f1::/113" ];
            publicKey = "2p1Jqs3bkXbXHFWE6vp1yxHIFoUaZQEARS2nJzbkuBA=";
          }
        ];
      };
    };
  };
}