{ config, lib, pkgs, ... }: with lib; let hostname = config.instance.hostname; domain-name = config.fudo.hosts.${hostname}.domain; domain = config.fudo.domains.${domain-name}; cfg = config.fudo.services.postgresql; zone-name = domain.zone; host-secrets = config.fudo.secrets.host-secrets.${hostname}; postgresEnabled = domain.postgresql-server == hostname; publicNetwork = let site-name = config.fudo.hosts.${hostname}.site; in config.fudo.sites.${site-name}.local-gateway == null; isPostgresHost = hostname == domain.postgresql-server; postgresql-hostname = "postgresql.${domain-name}"; acme-copies = config.fudo.acme.host-domains.${hostname}; postgresUser = config.systemd.services.postgresql.serviceConfig.User; in { options.fudo.services.postgresql = with types; { state-directory = mkOption { type = str; description = "Path at which to store PostgreSQL state."; }; keytab = mkOption { type = str; description = "Keytab for PostgreSQL."; }; }; config = mkIf postgresEnabled { fudo = { acme.host-domains.${hostname} = mkIf (publicNetwork && isPostgresHost) { ${postgresql-hostname}.local-copies = { postgresql = { user = postgresUser; dependent-services = [ "postgresql.service" ]; part-of = [ config.fudo.postgresql.systemd-target ]; }; }; }; secrets.host-secrets.${hostname}.postgres-keytab = mkIf (cfg.keytab != null) { source-file = cfg.keytab; target-file = "/run/postgresql/postgres.keytab"; user = postgresUser; }; zones.${zone-name}.aliases.postgresql = "${domain.postgresql-server}.${domain-name}."; postgresql = mkIf isPostgresHost (let ssl-config = optionalAttrs publicNetwork (let cert-copy = acme-copies.${postgresql-hostname}.local-copies.postgresql; in { ssl-certificate = mkIf publicNetwork cert-copy.full-certificate; ssl-private-key = mkIf publicNetwork cert-copy.private-key; required-services = [ cert-copy.service ]; }); in { enable = true; keytab = mkIf (cfg.keytab != null) host-secrets.postgres-keytab.target-file; local-networks = config.instance.local-networks; state-directory = cfg.state-directory; required-services = [ config.fudo.secrets.secret-target ]; } // ssl-config); }; }; }