{
  config,
  lib,
  inputs,
  ...
}:

let
  cfg = config.bagel.services.grapevine;
  inherit (lib) mkEnableOption mkIf;
in

{
  imports = [
    inputs.grapevine.nixosModules.default
    ./hookshot.nix
  ];

  options.bagel.services.grapevine.enable = mkEnableOption "Grapevine";

  config = mkIf cfg.enable {
    services = {
      grapevine = {
        enable = true;
        settings = {
          listen = [
            {
              type = "tcp";
              address = "127.0.0.1";
              port = 6167;
            }
          ];
          server_name = "forkos.org";
          database.backend = "rocksdb";
        };
      };

      nginx = {
        upstreams.grapevine.servers."127.0.0.1:6167" = { };

        virtualHosts = {
          "matrix.forkos.org" = {
            forceSSL = true;
            enableACME = true;
            locations."/".proxyPass = "http://grapevine";
          };

          "forkos.org" = {
            forceSSL = true;
            enableACME = true;
            locations = {
              "= /.well-known/matrix/server".extraConfig = ''
                add_header Content-Type application/json;
                add_header Access-Control-Allow-Origin *;
                return 200 '{"m.server": "matrix.forkos.org:443"}';
              '';
              "= /.well-known/matrix/client".extraConfig = ''
                add_header Content-Type application/json;
                add_header Access-Control-Allow-Origin *;
                return 200 '{"m.homeserver": {"base_url": "https://matrix.forkos.org/"}, "m.identity_server": {"base_url": "https://matrix.org/"}, "org.matrix.msc3575.proxy": {"url": "https://matrix.forkos.org"}}';
              '';
            };
          };
        };
      };
    };
  };
}