{ config, lib, pkgs, ... }: with lib; let lemmyDbPasswd = pkgs.lib.passwd.stablerandom-passwd-file "lemmy-server-passwd" "lemmy-server-${config.instance.build-seed}"; cfg = config.fudo.services.lemmy; hostname = config.instance.hostname; domainName = config.fudo.hosts."${hostname}".domain; postgresqlServer = config.fudo.domains."${domainName}".postgresql-server; postgresqlFqdn = pkgs.lib.getHostFqdn postgresqlServer; isPostgresServer = hostname == postgresqlServer; hostSecrets = config.fudo.secrets.host-secrets."${hostname}"; in { options.fudo.services.lemmy = with types; { enable = mkEnableOption "Enable lemmy server."; hostname = mkOption { type = str; description = "Hostname at which this server will be reachable."; }; port = mkOption { type = port; description = "Port on which to listen for requests"; default = 8536; }; listen-ip = mkOption { type = str; description = "IP on which to listen for incoming requests."; default = "0.0.0.0"; }; }; config = mkIf cfg.enable { fudo = { secrets.host-secrets."${hostname}" = { dbLemmyPasswd = mkIf isPostgresServer { source-file = lemmyDbPasswd; target-file = "/run/postgres/lemmy.passwd"; user = config.systemd.services.postgresql.serviceConfig.User; }; lemmyEnv = mkIf cfg.enable { source-file = pkgs.writeText "lemmy.env" '' LEMMY_DATABASE_URL=postgres:///lemmy:${ readFile lemmyDbPasswd }@${postgresqlFqdn}:5432/lemmy ''; target-file = "/run/lemmy/env"; }; }; postgresql = mkIf isPostgresServer { databases.lemmy.users = config.instance.local-admins; users.lemmy = { password-file = hostSecrets.dbLemmyPasswd.target-file; databases.lemmy = { access = "CONNECT"; entity-access = { "ALL TABLES IN SCHEMA public" = "ALL PRIVILEGES"; "ALL SEQUENCES IN SCHEMA public" = "ALL PRIVILEGES"; }; }; }; }; }; systemd.services.lemmy = { requires = [ "fudo-secret-lemmyEnv.service" ]; after = [ "fudo-secret-lemmyEnv.service" ]; environment.LEMMY_DATABASE_URL = mkForce null; serviceConfig = mkIf cfg.enable { LoadCredential = [ "env:${hostSecrets.lemmyEnv.target-file}" ]; EnvironmentFile = "$$CREDENTIALS_DIRECTORY/env"; }; }; services.lemmy = mkIf cfg.enable { enable = true; settings = { hostname = cfg.hostname; federation.enabled = true; captcha.enabled = true; database = { user = "lemmy"; host = pkgs.lib.getHostFqdn postgresqlServer; database = "lemmy"; password = readFile lemmyDbPasswd; }; bind = cfg.listen-ip; port = cfg.port; }; }; networking.firewall = { allowedTCPPorts = [ cfg.port ]; allowedUDPPorts = [ cfg.port ]; }; }; }