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

with lib;
let
  cfg = config.services.sourcehut;
  scfg = cfg.hg;
  iniKey = "hg.sr.ht";
  statePath = "/var/lib/sourcehut/hgsrht";

  rcfg = config.services.redis;
  drv = pkgs.sourcehut.hgsrht;
in
{
  options.services.sourcehut.hg = {
    enable = mkEnableOption "git service";

    user = mkOption {
      type = types.str;
      internal = true;
      readOnly = true;
      default = "hg";
      description = ''
        User for hg.sr.ht.
      '';
    };

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

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

    cloneBundles = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Generate clonebundles (which require more disk space but dramatically speed up cloning large repositories).
      '';
    };
  };

  config = with scfg; lib.mkIf (cfg.enable && scfg.enable) {
    # In case it ever comes into being
    environment.etc."ssh/hgsrht-dispatch" = {
      mode = "0755";
      text = ''
        #! ${pkgs.stdenv.shell}
        ${cfg.python}/bin/gitsrht-dispatch "$@"
      '';
    };

    environment.systemPackages = [ pkgs.mercurial ];

    users = {
      users = {
        "${user}" = {
          isSystemUser = true;
          group = user;
          # Assuming hg.sr.ht needs this too
          shell = pkgs.bash;
          description = "hg.sr.ht user";
        };
      };

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

    services = {
      openssh.authorizedKeysCommand = ''/etc/ssh/hgsrht-dispatch "%u" "%h" "%t" "%k"'';
      openssh.authorizedKeysCommandUser = "root";
      openssh.extraConfig = ''
        PermitUserEnvironment SRHT_*
      '';

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

    systemd = {
      tmpfiles.rules = [
        # /var/log is owned by root
        "f /var/log/hg-srht-shell 0644 ${user} ${user} -"

        "d ${cfg.settings."${iniKey}".repos} 2755 ${user} ${user} -"
      ];

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

          path = [ pkgs.mercurial ];
          description = "hg.sr.ht website service";

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

        hgsrht-periodic = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
          after = [ "hgsrht.service" ];
          requires = [ "hgsrht.service" ];

          description = "hg.sr.ht periodic service";

          serviceConfig.Type = mkForce "oneshot";
          serviceConfig.Restart = mkForce "no";
          serviceConfig.ExecStart = "${cfg.python}/bin/hgsrht-periodic";
        };

        hgsrht-clonebundles = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
          after = [ "hgsrht.service" ];
          requires = [ "hgsrht.service" ];

          description = "hg.sr.ht periodic service";

          serviceConfig.Type = mkForce "oneshot";
          serviceConfig.Restart = mkForce "no";
          serviceConfig.ExecStart = "${cfg.python}/bin/hgsrht-periodic";
        };
      };
    };

    systemd.timers = {
      hgsrht-periodic = {
        description = "hgsrht periodic timer";
        wantedBy = [ "timers.target" ];
        timerConfig = {
          OnCalendar = "20min";
          Persistent = true;
        };
      };
      hgsrht-clonebundles = {
        description = "hgsrht daily timer";
        wantedBy = [ "timers.target" ];
        timerConfig = {
          OnCalendar = "daily";
          Persistent = true;
          AccuracySec = "1h";
        };
      };
    };

    services.sourcehut.settings = {
      # The authorized keys hook uses this to dispatch to various handlers
      # The format is a program to exec into as the key, and the user to match as the
      # value. When someone tries to log in as this user, this program is executed
      # and is expected to emit an AuthorizedKeys file.
      #
      # Uncomment the relevant lines to enable the various sr.ht dispatchers.
      "hg.sr.ht::dispatch"."/run/current-system/sw/bin/hgsrht-keys" = mkDefault "${user}:${user}";
    };

    # TODO: requires testing and addition of hg-specific requirements
    services.nginx.virtualHosts."hg.${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.hgsrht}/${pkgs.sourcehut.python.sitePackages}/hgsrht";
    };
  };
}