{ config, pkgs, inputs, ... }: let
  image = name: "ghcr.io/genudine/${name}/${name}:latest";
  port = n: builtins.toString ( 8201 + (n * 100) );
in {
  sops.secrets.metagame = {
    sopsFile = ../../../secrets/ps2live/saerro.yaml;
  };

  virtualisation.oci-containers.containers = {
    metagame = {
      image = image "metagame";
      environment = {
        PORT = port 1;
      };
      ports = [ "${port 1}:${port 1}" ];
      environmentFiles = [
        config.sops.secrets.metagame.path
      ];
    };

    aggpop = {
      image = "ps2.live/agg.ps2.live:latest";
      imageFile = inputs.ps2live.packages.${pkgs.system}.aggpop;
      environment = {
        ADDR = ":${port 0}";
        USE_STANDARDIZATION = "1";
        DISABLE_FISU = "1";
      };
      ports = [ "${port 0}:${port 0}" ];
    };
  };

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

      systemctl restart podman-metagame
    '';
  };

  systemd.timers.restart-upgrade-aggmeta = {
    wantedBy = [ "timers.target" "podman-metagame.service" ];
    timerConfig = {
      Unit = "restart-upgrade-aggmeta.service";
      OnUnitActiveSec = "360m";
    };
  };

  systemd.services.start-aggpop-if-stopped = {
    serviceConfig.Type = "oneshot";
    script = ''
      curl --connect-timeout 3 -sSL localhost:${port 0} || \
        systemctl restart podman-aggpop
    '';
  };

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