{ pkgs, config, ...}: let
  nxperm = {
    owner = "nextcloud";
    group = "nextcloud";
    mode  = "0440";
  };
in {
  imports = [
    ./nextcloud/collobara.nix
  ];
  sops.secrets."nextcloud/adminPass" = nxperm;
  sops.secrets."nextcloud/s3secret" = nxperm;
  
  services.nextcloud = {
    enable = true;
    package = pkgs.nextcloud33;
    hostName = "localhost";
    settings = {
      trusted_domains = [
        "cloud.crompton.cc"
        "nextcloud.syzygial.cc"
      ];
    
      trusted_proxies = [
        "127.0.0.1"
      ];      

      overwriteprotocol = "https";
    };

    config = {
      adminuser = "CromptonAdmin";
      adminpassFile = config.sops.secrets."nextcloud/adminPass".path;

      dbtype = "pgsql";
      dbname = "nextcloud";
      dbuser = "nextcloud";

      dbhost = "/run/postgresql";

      objectstore.s3 = {
        enable = true;
        bucket = "nextcloud";
        verify_bucket_exists = false;
        key = "nextcloud";
        secretFile = config.sops.secrets."nextcloud/s3secret".path;
        region = "us-east-1";
        hostname = "100.64.0.4";
        port = 9000;
        useSsl = false;
        usePathStyle = true;
      };
    };
  };

  # systemd.services.nextcloud-setup = {
  #   requires = [ "postgresql.service" ];
  #   after = [ "postgresql.service" ];
  #   path = config.users.users.nextcloud.packages;
  #   script = ''
  #     if [[ ! -e /var/lib/nextcloud/store-apps/recognize/node_modules/@tensorflow/tfjs-node/lib/napi-v8/tfjs_binding.node ]]; then
  #       if [[ -d /var/lib/nextcloud/store-apps/recognize/node_modules/ ]]; then
  #         cd /var/lib/nextcloud/store-apps/recognize/node_modules/
  #         npm rebuild @tensorflow/tfjs-node --build-addon-from-source
  #       fi
  #     fi
  #   '';
  # };

  systemd.services.phpfpm-nextcloud = {
    path = config.users.users.nextcloud.packages;
  };

  users.users.nextcloud = {
    shell = pkgs.bashInteractive;
    packages = with pkgs; [
      # generate video thumbnails with preview generator
      ffmpeg_7-headless
      # required for recognize app
      nodejs_20 # runtime and installation requirement
      node-pre-gyp # installation requirement
      util-linux # runtime requirement for taskset
    ];
  };
  
  services.nginx.virtualHosts."localhost".listen = [ { addr = "127.0.0.1"; port = 8000; } ];
  
  services.caddy.virtualHosts = {
    "cloud.crompton.cc" = {
      serverAliases = [
        "nextcloud.syzygial.cc"
      ];
      extraConfig = ''
        reverse_proxy 127.0.0.1:8000
      '';
    };
  };
  
  services.postgresql = {
    enable = true;
    settings.port = 5432;
    ensureDatabases = [
      "nextcloud"
    ];
    ensureUsers = [{
      name = "nextcloud";
      ensureDBOwnership = true;
      ensureClauses = {
        createdb = true;
      };
    }];
  };
}
