# https://mich-murphy.com/configure-nextcloud-nixos/
{
  pkgs,
  config,
  common,
  ...
}:
let
  adminPassKey = "nextcloud/admin-pass";
  domain = "beta.nextcloud.${common.domain}";
  dbname = "nextcloud";
  dbuser = dbname;
in
{
  security.acme = {
    acceptTerms = true;
    certs.${config.services.nextcloud.hostName}.email = "acme@${common.domain}";
  };

  services = {
    nextcloud = {
      enable = false;

      autoUpdateApps.enable = true;

      config = {
        adminpassFile = config.sops.secrets.${adminPassKey}.path;
        dbtype = "pgsql";
        dbname = dbname;
        dbuser = dbuser;
        # default directory for postgresql, ensures automatic setup of db
        dbhost = "/run/postgresql";
        adminuser = "admin";
      };

      extraApps = {
        inherit (config.services.nextcloud.package.packages.apps)
          contacts
          deck
          notes
          tasks
          ;
      };
      extraAppsEnable = true;

      hostName = domain;
      https = true;

      maxUploadSize = "0"; # No max limit
      package = pkgs.nextcloud31;

      settings = {
        default_phone_region = "NO";
        trusted_domains = [
          domain
        ];
      };
    };

    nginx.virtualHosts.${config.services.nextcloud.hostName} = {
      forceSSL = true;
      enableACME = true;
    };

    postgresql = {
      ensureDatabases = [ dbname ];
      ensureUsers = [
        {
          name = dbuser;
          ensureDBOwnership = true;
        }
      ];
    };
    postgresqlBackup = {
      enable = true;
      location = "/data/backup/nextclouddb";
      databases = [ dbname ];
      # time to start backup in systemd.time format
      startAt = "*-*-* 23:15:00";
    };
  };

  sops.secrets.${adminPassKey}.neededForUsers = true;

  # ensure postgresql db is started with nextcloud
  systemd.services."nextcloud-setup" = {
    requires = [ "postgresql.service" ];
    after = [ "postgresql.service" ];
  };
}
