{ config, pkgs, inputs, ... }: let
  image = name: "ghcr.io/genudine/saerro/${name}:latest";
  port = n: builtins.toString (8100 + n);
  containerGenerics = {
    environmentFiles = [
      config.sops.secrets.saerro.path
    ];
    extraOptions = [
      "--pod=saerro"
    ];
    autoStart = true;
  };
  ctrToSysd = names: map (x: "podman-saerro_${x}.service") names;
in {

  sops.secrets.saerro = {
    sopsFile = ../../../secrets/ps2live/saerro.yaml;
  };

  virtualisation.oci-containers.containers = {
    saerro_api = {
      image = image "api";
      environment = {
        PORT = port 1;
        WEBSOCKET_HEALTHCHECK = "http://127.0.0.1:${port 2}/healthz";
      };
      dependsOn = [ "saerro_postgres" ];
    } // containerGenerics;

    saerro_ws = {
      image = "saerro/ws:latest";
      imageFile = inputs.saerro.packages.${pkgs.system}.ws;
      environment = {
        PORT = port 2;
      };
      dependsOn = [ "saerro_postgres" ];
    } // containerGenerics;

    saerro_maint = {
      image = "saerro/pruner:latest";
      imageFile = inputs.saerro.packages.${pkgs.system}.pruner;
      dependsOn = [ "saerro_postgres" ];
      
    } // containerGenerics;

    saerro_postgres = {
      image = "docker.io/library/postgres:17";
      volumes = [
        "saerrodb:/var/lib/postgresql/data"
      ];
    } // containerGenerics;
  };

  systemd.services.create-saerro-pod = {
    serviceConfig.Type = "oneshot";
    wantedBy = ctrToSysd [ "api" "ws" "maint" "postgres" ];
    script = ''
      ${pkgs.podman}/bin/podman pod exists saerro || \
      ${pkgs.podman}/bin/podman pod create -n saerro -p '0.0.0.0:${port 1}:${port 1}'
    '';
  };

  systemd.services.restart-upgrade-saerro = {
    serviceConfig.Type = "oneshot";
    script = ''
      ${pkgs.podman}/bin/podman pull ${config.virtualisation.oci-containers.containers.saerro_api.image}

      systemctl restart podman-saerro_api
    '';
  };

  systemd.timers.restart-upgrade-saerro = {
    wantedBy = [ "timers.target" "podman-saerro_api.service" ];
    timerConfig = {
      Unit = "restart-upgrade-saerro.service";
      OnUnitActiveSec = "420m";
    };
  };

  systemd.services.start-saerro-if-stopped = {
    serviceConfig.Type = "oneshot";
    script = ''
      systemctl start podman-saerro_ws
      systemctl start podman-saerro_pruner
    '';
  };

  systemd.timers.start-saerro-if-stopped = {
    wantedBy = [ "timers.target" "podman-saerro_ws.service" "podman-saerro_pruner.service" ];
    timerConfig = {
      Unit = "start-saerro-if-stopped.service";
      OnUnitActiveSec = "15m";
    };
  };
}
