{ config, containerCfg, pkgs, lib, builder, name, ... }:
let 
  serverCfg = config.syscfg.server;

  patchedInvidious = pkgs.invidious.overrideAttrs (oldAttrs: {
    postPatch = (oldAttrs.postPatch or "") + ''
      cp ${../data/invidious/login.cr} src/invidious/routes/login.cr
    '';
  });

  image = pkgs.dockerTools.streamLayeredImage {
    name = pkgs.invidious.name;
    tag = pkgs.invidious.version;

    contents = [ pkgs.cacert patchedInvidious ];
    config = {
      Entrypoint = [ "${patchedInvidious}/bin/invidious" ];
      ExposedPorts = { "3000/tcp" = {}; };
      Env = [ 
        "SSL_CERT_FILE=${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt"
        "NIX_SSL_CERT_FILE=${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt"
      ];
    };
  };

in {
  requires = {
    secrets = [ name ];
    databases = [ name ];
  };

  runtime = {
    paths = [{
      path="${serverCfg.path.config.path}/invidious";
      mode = "0755";
    }];

    containers = {
      server = builder.mkContainer {
        subdomain = containerCfg.subdomain;
        imageStream = image;
        port = 3000;
        secret = name;
        extraLabels = {
          "traefik.http.routers.${containerCfg.subdomain}-login.rule" = "Host(`${containerCfg.subdomain}.${serverCfg.domain}`) && Path(`/login`) ";
          "traefik.http.routers.${containerCfg.subdomain}-login.middlewares" = if serverCfg.containers?authentik then "authentik" else "";
          "traefik.http.routers.${containerCfg.subdomain}-login.priority" = "100";
          "traefik.http.routers.${containerCfg.subdomain}-login.entrypoints" = "web-secure";
          "traefik.http.routers.${containerCfg.subdomain}-login.tls" = "true";
        };
        extraEnv = {
          INVIDIOUS_CONFIG_FILE = "/data/config.yml";
        };
        overrides = {
          volumes = [
            "${serverCfg.path.config.path}/invidious:/data:ro"
          ];
        };
      };

      companion = builder.mkContainer {
        image = "quay.io/invidious/invidious-companion:latest";
        port = 8282;
        secret = name; #SERVER_SECRET_KEY = INVIDIOUS_COMPANION_KEY
        extraOptions = [
          "--cap-drop=all"
          "--security-opt=no-new-privileges"
        ];
      };
    };

    setup = {
      trigger = "server";
      envFile = [ config.sops.secrets."INVIDIOUS".path config.sops.secrets."CUSTOM".path ];
      script = pkgs.writeShellScript "setup" ''
        export DB_HOST=${builder.host}
        export INVIDIOUS_DOMAIN=${containerCfg.subdomain}.${serverCfg.domain}

        ${pkgs.gettext}/bin/envsubst < "${../data/invidious/config.yml}" > "${serverCfg.path.config.path}/invidious/config.yml"
      '';
    };
  };
}
