{ config, lib, pkgs, ... }:

let
  tracktrain-config = ''
    dbstring: "dbname=tracktrain"
    gtfs: /persist/gtfs.zip
    assets: ${pkgs.tracktrain}/assets

    warp:
      port: 4000

    login:
      enable: true
      url: https://login.infra4future.de
      clientName: tracktrain
      # clientSecret defined in env file

    logging:
      ntfyTopic: ping.stuebinm.eu/monit
      name: ilztalbahn
  '';
in
{
  sops.secrets = {
    "tracktrain/env" = {};
  };

  services.nginx.virtualHosts."tracktrain.ilztalbahn.eu" = {
    enableACME = true;
    forceSSL = true;
    locations."/" = {
      proxyPass = "http://${config.containers.tracktrain.localAddress}:4000";
      proxyWebsockets = true;
    };
    # note: this shadows the /metrics endpoint of tracktrain
    # in case you remove this, please consider putting something
    # else here to keep it from being publicly scrapable
    locations."/metrics/" = {
      proxyPass = "http://${config.containers.tracktrain.localAddress}:2342";
      proxyWebsockets = true;
      extraConfig = ''
        rewrite  ^/metrics/(.*)  /$1 break;
      '';
    };
  };

  hacc.containers.tracktrain = {
    bindSecrets = true;

    config = { config, lib, pkgs, ... }: {

      systemd.services.tracktrain = {
        enable = true;

        description = "tracks trains, hopefully";
        wantedBy = [ "multi-user.target" ];
        requires = [ "network.target" ];
        after = [ "network.target" ];
        serviceConfig = {
          Type = "simple";
          EnvironmentFile = "/secrets/env";
          DynamicUser = true;
        };
        path = [ pkgs.wget pkgs.ntfy-sh ];
        script = ''
          cd /tmp
          ln -sf ${pkgs.writeText "tracktrain-config.yaml" tracktrain-config} config.yaml
          sleep 3
          ${pkgs.tracktrain}/bin/tracktrain +RTS -T
        '';
      };

      systemd.services.postgresql.wantedBy = [ "tracktrain.service" ];

      services.postgresql = {
        enable = true;
        package = pkgs.postgresql_15;
        ensureDatabases = [ "tracktrain" ];
        ensureUsers = [ {
          name = "tracktrain";
          ensureDBOwnership = true;
        } ];
        authentication = ''
          local all all trust
        '';
      };

      services.prometheus = {
        enable = true;
        port = 9001;
        scrapeConfigs = [ {
          job_name = "tracktrain";
          static_configs = [{
            targets = [  "0.0.0.0:4000" ];
          }];
        } ];
      };

      systemd.services.grafana.serviceConfig.EnvironmentFile =
        "/secrets/env";
      hacc.bindToPersist = [ "/var/lib/grafana" ];
    };
  };

}