{
  flake,
  lib,
  config,
  ...
}:
let
  inherit (flake.config.machines.devices) ceres mars deimos;
  inherit (flake.config.services.instances) searx web;
  configHelpers = {
    service = searx;
    hostname = config.networking.hostName;
    localhost = web.localhost.address0;
    host = configHelpers.service.domains.url0;
  };
  configPath = ./config;
  configImports = {
    general = import (configPath + /general.nix);
    ui = import (configPath + /ui.nix);
    search = import (configPath + /search.nix);
    server = import (configPath + /server.nix) { inherit config flake configHelpers; };
    engines = import (configPath + /engines.nix) { inherit lib; };
    outgoing = import (configPath + /outgoing.nix);
    enabled_plugins = import (configPath + /plugins.nix);
  };

in
{
  services = {
    searx = {
      enable = true;
      redisCreateLocally = true;
      uwsgiConfig = {
        socket = "/run/searx/searx.sock";
        http = ":${builtins.toString configHelpers.service.ports.port0}";
        chmod-socket = "660";
      };
      settings = configImports;
    };
  }
  // (
    if configHelpers.hostname == ceres.name then
      {
        caddy = {
          virtualHosts = {
            "${configHelpers.host}" = {
              extraConfig = ''
                @allowed_ips {
                  remote_ip ${mars.wireguard.ip0} ${deimos.wireguard.ip0}
                }

                handle @allowed_ips {
                  redir /.well-known/carddav /remote.php/dav/ 301
                  redir /.well-known/caldav /remote.php/dav/ 301
                  reverse_proxy ${ceres.wireguard.ip0}:${toString configHelpers.service.ports.port0}
                }
                handle {
                  respond "Access Denied" 403
                }
                tls ${configHelpers.service.ssl.cert} ${configHelpers.service.ssl.key}
              '';
            };
          };
        };
      }
    else
      { }
  );

  users.groups.searx.members = [ "caddy" ];
  # systemd.services.caddy.serviceConfig.ProtectHome = false;

  sops =
    let
      sopsPath = secret: {
        path = "${configHelpers.service.sops.path0}/${configHelpers.service.name}-${secret}";
        owner = configHelpers.service.name;
        mode = "600";
      };
    in
    {
      secrets = builtins.listToAttrs (
        map
          (secret: {
            name = "${configHelpers.service.name}-${secret}";
            value = sopsPath secret;
          })
          [
            "key"
          ]
      );
    };

  networking = {
    firewall = {
      interfaces.wg0.allowedTCPPorts = [
        configHelpers.service.ports.port0
      ];
    };
  };
}
