{ pkgs, lib, config, ... }:
let
  inherit (builtins) readFile;
  inherit (builtins.extraBuiltins) pass;
  inherit (lib) types;
  inherit (config) networking;
  inherit (config.services) gitolite;
  inherit (config.users) users groups;
  gitolite-admin = "julm";
in
{
  # Make confortable to call gitolite from a shell
  # (but mind to prefix it by sudo -u git)
  environment.systemPackages = [ pkgs.gitolite ];

  services = {
    gitolite = {
      enable = true;
      user   = "git";
      group  = users."git-daemon".name;
      adminPubkey = (readFile ../../../sec/ssh/julm.pub);
      extraGitoliteRc = ''
        $RC{UMASK}           = 0027; # NOTE: no quote around in Perl, so it's octal
        $RC{LOG_DEST}        = 'repo-log,syslog';
        $RC{LOG_FACILITY}    = 'local0';
        #$RC{GIT_CONFIG_KEYS} = 'hooks.* gitweb.*';
        $RC{GIT_CONFIG_KEYS} = '.*';
        #$RC{LOCAL_CODE} = "$rc{GL_ADMIN_BASE}/local"
        #  if -d "$rc{GL_ADMIN_BASE}/local";
        $RC{LOCAL_CODE} = "$ENV{HOME}/local";
        push(@{$RC{ENABLE}}, ( 'Alias'
                             , 'cgit'
                               # NOTE: without this "cgit" option,
                               # the repositories' "description" files are not modified
                             , 'D'
                             , 'Shell ${gitolite-admin}'
                             , 'create'
                             , 'expand-deny-messages'
                             , 'fork'
                             , 'keysubdirs-as-groups'
                             , 'readme'
                             , (-d "$ENV{HOME}/local" ? 'repo-specific-hooks' : ())
                             , 'ssh-authkeys-split'
                             ));
      '';
    };
  };
  systemd.services.gitolite-init = {
    preStart = ''
      # Allow git-daemon to enter ~git
      chmod g+x "${gitolite.dataDir}"
      install -D -d -o ${gitolite.user} -g ${gitolite.group} -m 750 \
       ${gitolite.dataDir}/local \
       ${gitolite.dataDir}/local/hooks \
       ${gitolite.dataDir}/local/hooks/common \
       ${gitolite.dataDir}/local/hooks/repo-specific
    '';
  };
  systemd.services.git-daemon = {
    # NOTE: not using nixpkgs' gitDaemon, to avoid running it as root.
    after = [ "network.target" ];
    wantedBy = [ "multi-user.target" ];
    serviceConfig = {
      User       = users."git-daemon".name;
      Group      = groups."git-daemon".name;
      Restart    = "always";
      RestartSec = 5;
    };
    script = "${pkgs.git}/bin/git daemon --verbose --reuseaddr"
      + " --base-path=${gitolite.dataDir}/repositories"
      #+ (optionalString (cfg.listenAddress != "") "--listen=${cfg.listenAddress} ")
      #+ "--port=${toString cfg.port} "
      ;
  };
  users.users."git-daemon" = {
    uid = config.ids.uids.git;
    description = "Git daemon user";
  };
}