{ config, lib, pkgs, ... }:
with lib;
let
  cfg = config.services.moinmoin;
  python = pkgs.python27;
  pkg = python.pkgs.moinmoin;
  dataDir = "/var/lib/moin";
  usingGunicorn = cfg.webServer == "nginx-gunicorn" || cfg.webServer == "gunicorn";
  usingNginx = cfg.webServer == "nginx-gunicorn";
  user = "moin";
  group = "moin";
  uLit = s: ''u"${s}"'';
  indentLines = n: str: concatMapStrings (line: "${fixedWidthString n " " " "}${line}\n") (splitString "\n" str);
  moinCliWrapper = wikiIdent: pkgs.writeShellScriptBin "moin-${wikiIdent}" ''
    ${pkgs.su}/bin/su -s ${pkgs.runtimeShell} -c "${pkg}/bin/moin --config-dir=/var/lib/moin/${wikiIdent}/config $*" ${user}
  '';
  wikiConfig = wikiIdent: w: ''
    # -*- coding: utf-8 -*-
    from MoinMoin.config import multiconfig, url_prefix_static
    class Config(multiconfig.DefaultConfig):
        ${optionalString (w.webLocation != "/") ''
          url_prefix_static = '${w.webLocation}' + url_prefix_static
        ''}
        sitename = u'${w.siteName}'
        page_front_page = u'${w.frontPage}'
        data_dir = '${dataDir}/${wikiIdent}/data'
        data_underlay_dir = '${dataDir}/${wikiIdent}/underlay'
        language_default = u'${w.languageDefault}'
        ${optionalString (w.superUsers != []) ''
          superuser = [${concatMapStringsSep ", " uLit w.superUsers}]
        ''}
    ${indentLines 4 w.extraConfig}
  '';
  wikiConfigFile = name: wiki: pkgs.writeText "${name}.py" (wikiConfig name wiki);
in
{
  options.services.moinmoin = with types; {
    enable = mkEnableOption "MoinMoin Wiki Engine";
    webServer = mkOption {
      type = enum [ "nginx-gunicorn" "gunicorn" "none" ];
      default = "nginx-gunicorn";
      example = "none";
      description = ''
        Which web server to use to serve the wiki.
        Use