summary refs log tree commit diff
path: root/nixos/modules/services/web-apps/mediawiki.nix
blob: ce7bcd94b3f014102667f3e134db42f648380b76 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
{ config, pkgs, lib, ... }:

let

  inherit (lib) mkDefault mkEnableOption mkForce mkIf mkMerge mkOption;
  inherit (lib) concatStringsSep literalExpression mapAttrsToList optional optionals optionalString types;

  cfg = config.services.mediawiki;
  fpm = config.services.phpfpm.pools.mediawiki;
  user = "mediawiki";
  group =
    if cfg.webserver == "apache" then
      config.services.httpd.group
    else if cfg.webserver == "nginx" then
      config.services.nginx.group
    else "mediawiki";

  cacheDir = "/var/cache/mediawiki";
  stateDir = "/var/lib/mediawiki";

  pkg = pkgs.stdenv.mkDerivation rec {
    pname = "mediawiki-full";
    version = src.version;
    src = cfg.package;

    installPhase = ''
      mkdir -p $out
      cp -r * $out/

      rm -rf $out/share/mediawiki/skins/*
      rm -rf $out/share/mediawiki/extensions/*

      ${concatStringsSep "\n" (mapAttrsToList (k: v: ''
        ln -s ${v} $out/share/mediawiki/skins/${k}
      '') cfg.skins)}

      ${concatStringsSep "\n" (mapAttrsToList (k: v: ''
        ln -s ${if v != null then v else "$src/share/mediawiki/extensions/${k}"} $out/share/mediawiki/extensions/${k}
      '') cfg.extensions)}
    '';
  };

  mediawikiScripts = pkgs.runCommand "mediawiki-scripts" {
    nativeBuildInputs = [ pkgs.makeWrapper ];
    preferLocalBuild = true;
  } ''
    mkdir -p $out/bin
    for i in changePassword.php createAndPromote.php userOptions.php edit.php nukePage.php update.php; do
      makeWrapper ${pkgs.php}/bin/php $out/bin/mediawiki-$(basename $i .php) \
        --set MEDIAWIKI_CONFIG ${mediawikiConfig} \
        --add-flags ${pkg}/share/mediawiki/maintenance/$i
    done
  '';

  dbAddr = if cfg.database.socket == null then
    "${cfg.database.host}:${toString cfg.database.port}"
  else if cfg.database.type == "mysql" then
    "${cfg.database.host}:${cfg.database.socket}"
  else if cfg.database.type == "postgres" then
    "${cfg.database.socket}"
  else
    throw "Unsupported database type: ${cfg.database.type} for socket: ${cfg.database.socket}";

  mediawikiConfig = pkgs.writeText "LocalSettings.php" ''
    <?php
      # Protect against web entry
      if ( !defined( 'MEDIAWIKI' ) ) {
        exit;
      }

      $wgSitename = "${cfg.name}";
      $wgMetaNamespace = false;

      ## The URL base path to the directory containing the wiki;
      ## defaults for all runtime URL paths are based off of this.
      ## For more information on customizing the URLs
      ## (like /w/index.php/Page_title to /wiki/Page_title) please see:
      ## https://www.mediawiki.org/wiki/Manual:Short_URL
      $wgScriptPath = "${lib.optionalString (cfg.webserver == "nginx") "/w"}";

      ## The protocol and server name to use in fully-qualified URLs
      $wgServer = "${cfg.url}";

      ## The URL path to static resources (images, scripts, etc.)
      $wgResourceBasePath = $wgScriptPath;

      ${lib.optionalString (cfg.webserver == "nginx") ''
        $wgArticlePath = "/wiki/$1";
        $wgUsePathInfo = true;
      ''}

      ## The URL path to the logo.  Make sure you change this from the default,
      ## or else you'll overwrite your logo when you upgrade!
      $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";

      ## UPO means: this is also a user preference option

      $wgEnableEmail = true;
      $wgEnableUserEmail = true; # UPO

      $wgPasswordSender = "${cfg.passwordSender}";

      $wgEnotifUserTalk = false; # UPO
      $wgEnotifWatchlist = false; # UPO
      $wgEmailAuthentication = true;

      ## Database settings
      $wgDBtype = "${cfg.database.type}";
      $wgDBserver = "${dbAddr}";
      $wgDBport = "${toString cfg.database.port}";
      $wgDBname = "${cfg.database.name}";
      $wgDBuser = "${cfg.database.user}";
      ${optionalString (cfg.database.passwordFile != null) "$wgDBpassword = file_get_contents(\"${cfg.database.passwordFile}\");"}

      ${optionalString (cfg.database.type == "mysql" && cfg.database.tablePrefix != null) ''
        # MySQL specific settings
        $wgDBprefix = "${cfg.database.tablePrefix}";
      ''}

      ${optionalString (cfg.database.type == "mysql") ''
        # MySQL table options to use during installation or update
        $wgDBTableOptions = "ENGINE=InnoDB, DEFAULT CHARSET=binary";
      ''}

      ## Shared memory settings
      $wgMainCacheType = CACHE_NONE;
      $wgMemCachedServers = [];

      ${optionalString (cfg.uploadsDir != null) ''
        $wgEnableUploads = true;
        $wgUploadDirectory = "${cfg.uploadsDir}";
      ''}

      $wgUseImageMagick = true;
      $wgImageMagickConvertCommand = "${pkgs.imagemagick}/bin/convert";

      # InstantCommons allows wiki to use images from https://commons.wikimedia.org
      $wgUseInstantCommons = false;

      # Periodically send a pingback to https://www.mediawiki.org/ with basic data
      # about this MediaWiki instance. The Wikimedia Foundation shares this data
      # with MediaWiki developers to help guide future development efforts.
      $wgPingback = true;

      ## If you use ImageMagick (or any other shell command) on a
      ## Linux server, this will need to be set to the name of an
      ## available UTF-8 locale
      $wgShellLocale = "C.UTF-8";

      ## Set $wgCacheDirectory to a writable directory on the web server
      ## to make your wiki go slightly faster. The directory should not
      ## be publicly accessible from the web.
      $wgCacheDirectory = "${cacheDir}";

      # Site language code, should be one of the list in ./languages/data/Names.php
      $wgLanguageCode = "en";

      $wgSecretKey = file_get_contents("${stateDir}/secret.key");

      # Changing this will log out all existing sessions.
      $wgAuthenticationTokenVersion = "";

      ## For attaching licensing metadata to pages, and displaying an
      ## appropriate copyright notice / icon. GNU Free Documentation
      ## License and Creative Commons licenses are supported so far.
      $wgRightsPage = ""; # Set to the title of a wiki page that describes your license/copyright
      $wgRightsUrl = "";
      $wgRightsText = "";
      $wgRightsIcon = "";

      # Path to the GNU diff3 utility. Used for conflict resolution.
      $wgDiff = "${pkgs.diffutils}/bin/diff";
      $wgDiff3 = "${pkgs.diffutils}/bin/diff3";

      # Enabled skins.
      ${concatStringsSep "\n" (mapAttrsToList (k: v: "wfLoadSkin('${k}');") cfg.skins)}

      # Enabled extensions.
      ${concatStringsSep "\n" (mapAttrsToList (k: v: "wfLoadExtension('${k}');") cfg.extensions)}


      # End of automatically generated settings.
      # Add more configuration options below.

      ${cfg.extraConfig}
  '';

  withTrailingSlash = str: if lib.hasSuffix "/" str then str else "${str}/";
in
{
  # interface
  options = {
    services.mediawiki = {

      enable = mkEnableOption (lib.mdDoc "MediaWiki");

      package = mkOption {
        type = types.package;
        default = pkgs.mediawiki;
        defaultText = literalExpression "pkgs.mediawiki";
        description = lib.mdDoc "Which MediaWiki package to use.";
      };

      finalPackage = mkOption {
        type = types.package;
        readOnly = true;
        default = pkg;
        defaultText = literalExpression "pkg";
        description = lib.mdDoc ''
          The final package used by the module. This is the package that will have extensions and skins installed.
        '';
      };

      name = mkOption {
        type = types.str;
        default = "MediaWiki";
        example = "Foobar Wiki";
        description = lib.mdDoc "Name of the wiki.";
      };

      url = mkOption {
        type = types.str;
        default =
          if cfg.webserver == "apache" then
            "${if cfg.httpd.virtualHost.addSSL || cfg.httpd.virtualHost.forceSSL || cfg.httpd.virtualHost.onlySSL then "https" else "http"}://${cfg.httpd.virtualHost.hostName}"
          else if cfg.webserver == "nginx" then
            let
              hasSSL = host: host.forceSSL || host.addSSL;
            in
            "${if hasSSL config.services.nginx.virtualHosts.${cfg.nginx.hostName} then "https" else "http"}://${cfg.nginx.hostName}"
          else
            "http://localhost";
        defaultText = literalExpression ''
          if cfg.webserver == "apache" then
            "''${if cfg.httpd.virtualHost.addSSL || cfg.httpd.virtualHost.forceSSL || cfg.httpd.virtualHost.onlySSL then "https" else "http"}://''${cfg.httpd.virtualHost.hostName}"
          else
            "http://localhost";
        '';
        example = "https://wiki.example.org";
        description = lib.mdDoc "URL of the wiki.";
      };

      uploadsDir = mkOption {
        type = types.nullOr types.path;
        default = "${stateDir}/uploads";
        description = lib.mdDoc ''
          This directory is used for uploads of pictures. The directory passed here is automatically
          created and permissions adjusted as required.
        '';
      };

      passwordFile = mkOption {
        type = types.path;
        description = lib.mdDoc "A file containing the initial password for the admin user.";
        example = "/run/keys/mediawiki-password";
      };

      passwordSender = mkOption {
        type = types.str;
        default =
          if cfg.webserver == "apache" then
            if cfg.httpd.virtualHost.adminAddr != null then
              cfg.httpd.virtualHost.adminAddr
            else
              config.services.httpd.adminAddr else "root@localhost";
        defaultText = literalExpression ''
          if cfg.webserver == "apache" then
            if cfg.httpd.virtualHost.adminAddr != null then
              cfg.httpd.virtualHost.adminAddr
            else
              config.services.httpd.adminAddr else "root@localhost"
        '';
        description = lib.mdDoc "Contact address for password reset.";
      };

      skins = mkOption {
        default = {};
        type = types.attrsOf types.path;
        description = lib.mdDoc ''
          Attribute set of paths whose content is copied to the {file}`skins`
          subdirectory of the MediaWiki installation in addition to the default skins.
        '';
      };

      extensions = mkOption {
        default = {};
        type = types.attrsOf (types.nullOr types.path);
        description = lib.mdDoc ''
          Attribute set of paths whose content is copied to the {file}`extensions`
          subdirectory of the MediaWiki installation and enabled in configuration.

          Use `null` instead of path to enable extensions that are part of MediaWiki.
        '';
        example = literalExpression ''
          {
            Matomo = pkgs.fetchzip {
              url = "https://github.com/DaSchTour/matomo-mediawiki-extension/archive/v4.0.1.tar.gz";
              sha256 = "0g5rd3zp0avwlmqagc59cg9bbkn3r7wx7p6yr80s644mj6dlvs1b";
            };
            ParserFunctions = null;
          }
        '';
      };

      webserver = mkOption {
        type = types.enum [ "apache" "none" "nginx" ];
        default = "apache";
        description = lib.mdDoc "Webserver to use.";
      };

      database = {
        type = mkOption {
          type = types.enum [ "mysql" "postgres" "sqlite" "mssql" "oracle" ];
          default = "mysql";
          description = lib.mdDoc "Database engine to use. MySQL/MariaDB is the database of choice by MediaWiki developers.";
        };

        host = mkOption {
          type = types.str;
          default = "localhost";
          description = lib.mdDoc "Database host address.";
        };

        port = mkOption {
          type = types.port;
          default = if cfg.database.type == "mysql" then 3306 else 5432;
          defaultText = literalExpression "3306";
          description = lib.mdDoc "Database host port.";
        };

        name = mkOption {
          type = types.str;
          default = "mediawiki";
          description = lib.mdDoc "Database name.";
        };

        user = mkOption {
          type = types.str;
          default = "mediawiki";
          description = lib.mdDoc "Database user.";
        };

        passwordFile = mkOption {
          type = types.nullOr types.path;
          default = null;
          example = "/run/keys/mediawiki-dbpassword";
          description = lib.mdDoc ''
            A file containing the password corresponding to
            {option}`database.user`.
          '';
        };

        tablePrefix = mkOption {
          type = types.nullOr types.str;
          default = null;
          description = lib.mdDoc ''
            If you only have access to a single database and wish to install more than
            one version of MediaWiki, or have other applications that also use the
            database, you can give the table names a unique prefix to stop any naming
            conflicts or confusion.
            See <https://www.mediawiki.org/wiki/Manual:$wgDBprefix>.
          '';
        };

        socket = mkOption {
          type = types.nullOr types.path;
          default = if (cfg.database.type == "mysql" && cfg.database.createLocally) then
              "/run/mysqld/mysqld.sock"
            else if (cfg.database.type == "postgres" && cfg.database.createLocally) then
              "/run/postgresql"
            else
              null;
          defaultText = literalExpression "/run/mysqld/mysqld.sock";
          description = lib.mdDoc "Path to the unix socket file to use for authentication.";
        };

        createLocally = mkOption {
          type = types.bool;
          default = cfg.database.type == "mysql" || cfg.database.type == "postgres";
          defaultText = literalExpression "true";
          description = lib.mdDoc ''
            Create the database and database user locally.
            This currently only applies if database type "mysql" is selected.
          '';
        };
      };

      nginx.hostName = mkOption {
        type = types.str;
        example = literalExpression ''wiki.example.com'';
        default = "localhost";
        description = lib.mdDoc ''
          The hostname to use for the nginx virtual host.
          This is used to generate the nginx configuration.
        '';
      };

      httpd.virtualHost = mkOption {
        type = types.submodule (import ../web-servers/apache-httpd/vhost-options.nix);
        example = literalExpression ''
          {
            hostName = "mediawiki.example.org";
            adminAddr = "webmaster@example.org";
            forceSSL = true;
            enableACME = true;
          }
        '';
        description = lib.mdDoc ''
          Apache configuration can be done by adapting {option}`services.httpd.virtualHosts`.
          See [](#opt-services.httpd.virtualHosts) for further information.
        '';
      };

      poolConfig = mkOption {
        type = with types; attrsOf (oneOf [ str int bool ]);
        default = {
          "pm" = "dynamic";
          "pm.max_children" = 32;
          "pm.start_servers" = 2;
          "pm.min_spare_servers" = 2;
          "pm.max_spare_servers" = 4;
          "pm.max_requests" = 500;
        };
        description = lib.mdDoc ''
          Options for the MediaWiki PHP pool. See the documentation on `php-fpm.conf`
          for details on configuration directives.
        '';
      };

      extraConfig = mkOption {
        type = types.lines;
        description = lib.mdDoc ''
          Any additional text to be appended to MediaWiki's
          LocalSettings.php configuration file. For configuration
          settings, see <https://www.mediawiki.org/wiki/Manual:Configuration_settings>.
        '';
        default = "";
        example = ''
          $wgEnableEmail = false;
        '';
      };

    };
  };

  imports = [
    (lib.mkRenamedOptionModule [ "services" "mediawiki" "virtualHost" ] [ "services" "mediawiki" "httpd" "virtualHost" ])
  ];

  # implementation
  config = mkIf cfg.enable {

    assertions = [
      { assertion = cfg.database.createLocally -> (cfg.database.type == "mysql" || cfg.database.type == "postgres");
        message = "services.mediawiki.createLocally is currently only supported for database type 'mysql' and 'postgres'";
      }
      { assertion = cfg.database.createLocally -> cfg.database.user == user && cfg.database.name == cfg.database.user;
        message = "services.mediawiki.database.user must be set to ${user} if services.mediawiki.database.createLocally is set true";
      }
      { assertion = cfg.database.createLocally -> cfg.database.socket != null;
        message = "services.mediawiki.database.socket must be set if services.mediawiki.database.createLocally is set to true";
      }
      { assertion = cfg.database.createLocally -> cfg.database.passwordFile == null;
        message = "a password cannot be specified if services.mediawiki.database.createLocally is set to true";
      }
    ];

    services.mediawiki.skins = {
      MonoBook = "${cfg.package}/share/mediawiki/skins/MonoBook";
      Timeless = "${cfg.package}/share/mediawiki/skins/Timeless";
      Vector = "${cfg.package}/share/mediawiki/skins/Vector";
    };

    services.mysql = mkIf (cfg.database.type == "mysql" && cfg.database.createLocally) {
      enable = true;
      package = mkDefault pkgs.mariadb;
      ensureDatabases = [ cfg.database.name ];
      ensureUsers = [{
        name = cfg.database.user;
        ensurePermissions = { "${cfg.database.name}.*" = "ALL PRIVILEGES"; };
      }];
    };

    services.postgresql = mkIf (cfg.database.type == "postgres" && cfg.database.createLocally) {
      enable = true;
      ensureDatabases = [ cfg.database.name ];
      ensureUsers = [{
        name = cfg.database.user;
        ensureDBOwnership = true;
      }];
    };

    services.phpfpm.pools.mediawiki = {
      inherit user group;
      phpEnv.MEDIAWIKI_CONFIG = "${mediawikiConfig}";
      # https://www.mediawiki.org/wiki/Compatibility
      phpPackage = pkgs.php81;
      settings = (if (cfg.webserver == "apache") then {
        "listen.owner" = config.services.httpd.user;
        "listen.group" = config.services.httpd.group;
      } else if (cfg.webserver == "nginx") then {
        "listen.owner" = config.services.nginx.user;
        "listen.group" = config.services.nginx.group;
      } else {
        "listen.owner" = user;
        "listen.group" = group;
      }) // cfg.poolConfig;
    };

    services.httpd = lib.mkIf (cfg.webserver == "apache") {
      enable = true;
      extraModules = [ "proxy_fcgi" ];
      virtualHosts.${cfg.httpd.virtualHost.hostName} = mkMerge [
        cfg.httpd.virtualHost
        {
          documentRoot = mkForce "${pkg}/share/mediawiki";
          extraConfig = ''
            <Directory "${pkg}/share/mediawiki">
              <FilesMatch "\.php$">
                <If "-f %{REQUEST_FILENAME}">
                  SetHandler "proxy:unix:${fpm.socket}|fcgi://localhost/"
                </If>
              </FilesMatch>

              Require all granted
              DirectoryIndex index.php
              AllowOverride All
            </Directory>
          '' + optionalString (cfg.uploadsDir != null) ''
            Alias "/images" "${cfg.uploadsDir}"
            <Directory "${cfg.uploadsDir}">
              Require all granted
            </Directory>
          '';
        }
      ];
    };
    # inspired by https://www.mediawiki.org/wiki/Manual:Short_URL/Nginx
    services.nginx = lib.mkIf (cfg.webserver == "nginx") {
      enable = true;
      virtualHosts.${config.services.mediawiki.nginx.hostName} = {
        root = "${pkg}/share/mediawiki";
        locations = {
          "~ ^/w/(index|load|api|thumb|opensearch_desc|rest|img_auth)\\.php$".extraConfig = ''
            rewrite ^/w/(.*) /$1 break;
            include ${config.services.nginx.package}/conf/fastcgi_params;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_pass unix:${config.services.phpfpm.pools.mediawiki.socket};
          '';
          "/w/images/".alias = withTrailingSlash cfg.uploadsDir;
          # Deny access to deleted images folder
          "/w/images/deleted".extraConfig = ''
            deny all;
          '';
          # MediaWiki assets (usually images)
          "~ ^/w/resources/(assets|lib|src)".extraConfig = ''
            rewrite ^/w(/.*) $1 break;
            add_header Cache-Control "public";
            expires 7d;
          '';
          # Assets, scripts and styles from skins and extensions
          "~ ^/w/(skins|extensions)/.+\\.(css|js|gif|jpg|jpeg|png|svg|wasm|ttf|woff|woff2)$".extraConfig = ''
            rewrite ^/w(/.*) $1 break;
            add_header Cache-Control "public";
            expires 7d;
          '';

          # Handling for Mediawiki REST API, see [[mw:API:REST_API]]
          "/w/rest.php/".tryFiles = "$uri $uri/ /w/rest.php?$query_string";

          # Handling for the article path (pretty URLs)
          "/wiki/".extraConfig = ''
            rewrite ^/wiki/(?<pagename>.*)$ /w/index.php;
          '';

          # Explicit access to the root website, redirect to main page (adapt as needed)
          "= /".extraConfig = ''
            return 301 /wiki/Main_Page;
          '';

          # Every other entry point will be disallowed.
          # Add specific rules for other entry points/images as needed above this
          "/".extraConfig = ''
             return 404;
          '';
        };
      };
    };

    systemd.tmpfiles.rules = [
      "d '${stateDir}' 0750 ${user} ${group} - -"
      "d '${cacheDir}' 0750 ${user} ${group} - -"
    ] ++ optionals (cfg.uploadsDir != null) [
      "d '${cfg.uploadsDir}' 0750 ${user} ${group} - -"
      "Z '${cfg.uploadsDir}' 0750 ${user} ${group} - -"
    ];

    systemd.services.mediawiki-init = {
      wantedBy = [ "multi-user.target" ];
      before = [ "phpfpm-mediawiki.service" ];
      after = optional (cfg.database.type == "mysql" && cfg.database.createLocally) "mysql.service"
              ++ optional (cfg.database.type == "postgres" && cfg.database.createLocally) "postgresql.service";
      script = ''
        if ! test -e "${stateDir}/secret.key"; then
          tr -dc A-Za-z0-9 </dev/urandom 2>/dev/null | head -c 64 > ${stateDir}/secret.key
        fi

        echo "exit( wfGetDB( DB_MASTER )->tableExists( 'user' ) ? 1 : 0 );" | \
        ${pkgs.php}/bin/php ${pkg}/share/mediawiki/maintenance/eval.php --conf ${mediawikiConfig} && \
        ${pkgs.php}/bin/php ${pkg}/share/mediawiki/maintenance/install.php \
          --confpath /tmp \
          --scriptpath / \
          --dbserver "${dbAddr}" \
          --dbport ${toString cfg.database.port} \
          --dbname ${cfg.database.name} \
          ${optionalString (cfg.database.tablePrefix != null) "--dbprefix ${cfg.database.tablePrefix}"} \
          --dbuser ${cfg.database.user} \
          ${optionalString (cfg.database.passwordFile != null) "--dbpassfile ${cfg.database.passwordFile}"} \
          --passfile ${cfg.passwordFile} \
          --dbtype ${cfg.database.type} \
          ${cfg.name} \
          admin

        ${pkgs.php}/bin/php ${pkg}/share/mediawiki/maintenance/update.php --conf ${mediawikiConfig} --quick
      '';

      serviceConfig = {
        Type = "oneshot";
        User = user;
        Group = group;
        PrivateTmp = true;
      };
    };

    systemd.services.httpd.after = optional (cfg.webserver == "apache" && cfg.database.createLocally && cfg.database.type == "mysql") "mysql.service"
      ++ optional (cfg.webserver == "apache" && cfg.database.createLocally && cfg.database.type == "postgres") "postgresql.service";

    users.users.${user} = {
      group = group;
      isSystemUser = true;
    };
    users.groups.${group} = {};

    environment.systemPackages = [ mediawikiScripts ];
  };
}