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

with lib;

let cfg = config.services.glitchtip;
in {
  options.services.glitchtip = with types; {
    enable = mkOption {
      type = types.bool;
      default = false;
      description = "Enables glitchtip. This module is bring-your-own redis & postgres (look at redisUrl & databaseUrl); both are required for glitchtip to run without errors";
    };

    databaseUrl = mkOption {
      type = str;
      default = "postgres://glitchtip@localhost:5432/glitchtip";
      description = "how to connect to postgres. An empty database (e.g. created by services.postgresql.ensureDatabases) is sufficient; migrations will be run automatically on startup.";
    };

    redisUrl = mkOption {
      type = str;
      default = "redis://localhost";
      description = "how to connect to redis";
    };

    domain = mkOption {
      type = str;
      default = "http://localhost:${toString cfg.port}";
      description = "your glitchtip's public-facing domain. Must include the schema (http/https).";
    };

    package = mkOption {
      type = package;
      default = pkgs.glitchtip;
    };

    port = mkOption {
      type = port;
      default = 8000;
      description = "port for glitchtip's uwsgi server";
    };
  };

  config = mkIf cfg.enable {
    services.uwsgi = {
      enable = true;
      plugins = [ "python3" ];
      instance = {
        type = "normal";
        pythonPackages = _: [ cfg.package ];
        module = "glitchtip.wsgi:application";
        chdir = cfg.package;
        threads = 4;
        http = ":${toString cfg.port}";
        env = [
          "DATABASE_URL=${cfg.databaseUrl}"
          "GLITCHTIP_DOMAIN=${cfg.domain}"
          "REDIS_URL=${cfg.redisUrl}"
        ];
        hook-pre-app = ''
          exec:./manage.py migrate
        '';
      };
    };

    systemd.services."glitchtip-celery" = {
      enable = true;
      wantedBy = [ "uwsgi.service" ];
      serviceConfig.Type = "simple";
      path = [ cfg.package.dependencyEnv ];
      script = ''
        cd ${cfg.package}
        bin/run-celery-with-beat.sh
      '';
      environment = {
        DATABASE_URL = cfg.databaseUrl;
        REDIS_URL = cfg.redisUrl;
      };
    };
  };
}