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

with lib;
let
  cfg = config.services.sourcehut;
  cfgIni = cfg.settings;
  scfg = cfg.paste;
  iniKey = "paste.sr.ht";
  statePath = "/var/lib/sourcehut/pastesrht";

  rcfg = config.services.redis;
  drv = pkgs.sourcehut.pastesrht;
in
{
  options.services.sourcehut.paste = {
    enable = mkEnableOption "paste service";

    user = mkOption {
      type = types.str;
      default = "pastesrht";
      description = ''
        User for paste.sr.ht.
      '';
    };

    port = mkOption {
      type = types.port;
      default = 5011;
      description = ''
        Port on which the "paste" module should listen.
      '';
    };

    database = mkOption {
      type = types.str;
      default = "paste.sr.ht";
      description = ''
        PostgreSQL database name for paste.sr.ht.
      '';
    };
  };

  config = with scfg; lib.mkIf (cfg.enable && scfg.enable) {
    users = {
      users = {
        "${user}" = {
          isSystemUser = true;
          group = user;
          description = "paste.sr.ht user";
        };
      };

      groups = {
        "${user}" = { };
      };
    };

    services.postgresql = {
      authentication = ''
        local ${database} ${user} trust
      '';
      ensureDatabases = [ database ];
      ensureUsers = [
        {
          name = user;
          ensurePermissions = { "DATABASE \"${database}\"" = "ALL PRIVILEGES"; };
        }
      ];
    };

    systemd = {
      services = {
        pastesrht = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
          after = [ "postgresql.service" "network.target" ];
          requires = [ "postgresql.service" ];
          wantedBy = [ "multi-user.target" ];

          description = "paste.sr.ht website service";

          serviceConfig.ExecStart = "${cfg.python}/bin/gunicorn ${drv.pname}.app:app -b ${cfg.address}:${toString port}";
        };

        pastesrht-webhooks = {
          after = [ "postgresql.service" "network.target" ];
          requires = [ "postgresql.service" ];
          wantedBy = [ "multi-user.target" ];

          description = "paste.sr.ht webhooks service";
          serviceConfig = {
            Type = "simple";
            User = user;
            Restart = "always";
            ExecStart = "${cfg.python}/bin/celery -A ${drv.pname}.webhooks worker --loglevel INFO --pool eventlet";
          };

        };
      };
    };

    services.sourcehut.settings = {
    };

    services.nginx.virtualHosts."paste.${cfg.originBase}" = {
      forceSSL = true;
      locations."/".proxyPass = "http://${cfg.address}:${toString port}";
      locations."/query".proxyPass = cfgIni."meta.sr.ht".api-origin;
      locations."/static".root = "${pkgs.sourcehut.pastesrht}/${pkgs.sourcehut.python.sitePackages}/pastesrht";
    };
  };
}