{ config, containerCfg, pkgs, lib, builder, name, ... }:
let
  version = "latest";
  serverCfg = config.syscfg.server;
in {
  requires = {
    secrets = [ name ];
    databases = [ name ];
  };

  runtime = {
    paths = [
      {
        path = "${serverCfg.path.config.path}/freshrss";
        owner = "1000:1000";
        mode = "0755";
      }
    ];

    containers = {
      server = builder.mkContainer {
        subdomain = containerCfg.subdomain;
        image = "ghcr.io/freshrss/freshrss:${version}";
        port = 80;
        
        extraEnv = {
          CRON_MIN = "5,35";
          TRUSTED_PROXY = "10.0.0.0/8 192.168.0.1/16";
          LISTEN = "80";
          OIDC_ENABLED = "1";
          OIDC_PROVIDER_METADATA_URL = "https://${serverCfg.containers.authentik.subdomain}.${serverCfg.domain}/application/o/freshrss/.well-known/openid-configuration";
          OIDC_REMOTE_USER_CLAIM = "preferred_username";
          OIDC_CLIENT_ID = "freshrss";
          OIDC_SCOPES = "openid profile";
          OIDC_X_FORWARDED_HEADERS = "X-Forwarded-Host X-Forwarded-Port X-Forwarded-Proto";
        };

        overrides = {
          environmentFiles =  [ config.sops.secrets."FRESHRSS".path config.sops.secrets."CUSTOM".path ];
          volumes = ["${serverCfg.path.config.path}/freshrss:/var/www/FreshRSS/data"];
        };
      };
    };

    setup = {
      trigger = "server"; # Triggers atomic environment verification on main controller
      envFile = [ config.sops.secrets."FRESHRSS".path config.sops.secrets."CUSTOM".path];
      script = pkgs.writeShellScript "setup-freshrss" ''

        RSS="${pkgs.podman}/bin/podman --events-backend=none exec -u www-data freshrss-server"
        $RSS ./cli/prepare.php
        $RSS ./cli/do-install.php --default-user $DEFAULT_ADMIN_USERNAME --auth-type http_auth --base-url https://${containerCfg.subdomain}.${serverCfg.domain} --language en \
          --title RSS --api-enabled --db-type pgsql --db-host ${builder.host} --db-user freshrss_user --db-password $DB_PASSWORD --db-base freshrss_db
        $RSS ./cli/create-user.php --user $DEFAULT_ADMIN_USERNAME --password $DEFAULT_ADMIN_PASSWORD --email $DEFAULT_ADMIN_EMAIL
        $RSS ./cli/reconfigure.php
        # $RSS ./cli/access-permissions.sh
        
      '';
    };
  };
}
