{ config, flake, ... }:
let
  inherit (flake.config.services.instances)
    glance
    jellyfin
    web
    ;
  inherit (flake.config.machines.devices) ceres mars deimos;
  configHelpers = {
    service = glance;
    hostname = config.networking.hostName;
    localhost = web.localhost.address1;
    host = configHelpers.service.domains.url0;
  };
  configPath = ./config;
  configImports = {
    server = import (configPath + /server.nix) { inherit flake configHelpers; };
    branding = import (configPath + /branding.nix);
    theme = import (configPath + /theme.nix);
    pages = import (configPath + /pages.nix) { inherit config flake; };
  };
in
{
  services = {
    glance = {
      enable = true;
      settings = configImports;
    };
    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}
          '';
        };
      };
    };
  };
  sops =
    let
      sopsPath = secret: {
        path = "/run/secrets/${configHelpers.service.name}-${secret}";
        owner = "root";
        group = "root";
        mode = "644";
      };
    in
    {
      secrets = builtins.listToAttrs (
        map
          (secret: {
            name = "${configHelpers.service.name}-${secret}";
            value = sopsPath secret;
          })
          [
            # "key"
            # "${user0}-pass"
            jellyfin.name
          ]
      );
    };

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