{ config, pkgs, lib, ... }: 

let
  cfg = config.services.nextcloud;
  domain = "cloud.tx0.co";
  wrappers = config.security.wrapperDir;
  pg = config.services.postgresql.package;
in {
  services.nextcloud = {
    enable = true;

    hostName = domain;
    https = true;

    nginx.enable = true;
    maxUploadSize = "2048M";

    caching = {
      apcu = true;
      redis = true;
    };

    config = {
      dbtype = "pgsql";
      dbuser = "nextcloud";
      dbhost = "/tmp"; # nextcloud will add /.s.PGSQL.5432 by itself
      dbname = "nextcloud";
      adminuser = "root";
      adminpassFile = "${config.services.nextcloud.home}/adminpass";
    };
  };

  services.redis.enable = true;

  services.nginx.virtualHosts.${domain} = {
    forceSSL = true;
    enableACME = true;
  };
  
  services.postgresql.enable = true;

  # ensure that postgres is running *before* running the setup
  systemd.services.nextcloud-setup = {
    requires = [ "postgresql.service" ];
    after = [ "postgresql.service" ];

    preStart = lib.mkBefore ''
      if ! test -e "${cfg.home}/db-created"; then
        ${wrappers}/sudo -u postgres \
          ${pg}/bin/createuser \
            --login \
            --no-createdb \
            --no-createrole \
            --encrypted \
            nextcloud

        ${wrappers}/sudo -u postgres \
          ${pg}/bin/createdb \
            --owner=nextcloud \
            --encoding=UTF8 \
            nextcloud

        touch "${cfg.home}/db-created"
      fi
    '';
  };
}