{ config, ... }:

{
  services.phpfpm.pools.mediawiki.phpOptions = ''
    upload_max_filesize = 1024M;
    post_max_size = 1024M;
  '';

  services.mediawiki = {
    enable = true;
    name = "Fediversity Wiki";
    webserver = "nginx";
    nginx.hostName = "wiki.fediversity.eu";
    passwordFile = config.age.secrets.wiki-password.path;
    extraConfig = ''
      # Disable anonymous editing
      $wgGroupPermissions['*']['edit'] = false;
      $wgEnableUploads  = true;
      $wgFileExtensions = array('png', 'jpg', 'jpeg', 'svg', 'pdf', 'odt', 'ods', 'brd', 'sch', 'JPG', 'PNG', 'JPEG', 'SVG', 'json', 'mkv', 'mp4', 'gif');
      $wgUseImageMagick = true;
      $wgMaxShellMemory = 524288;
      $wgSVGMetadataCutoff = 1024*1024;
      $wgAllowExternalImages = false;

      ## Permissions
      $wgGroupPermissions['*']['edit'] = false;
      $wgGroupPermissions['*']['createaccount'] = true;
      $wgGroupPermissions['*']['autocreateaccount'] = true;
      $wgGroupPermissions['user']['edit'] = true;
      $wgGroupPermissions['user']['createaccount'] = true;
      $wgGroupPermissions['user']['editmyprivateinfo'] = true;
      $wgGroupPermissions['sysop']['interwiki'] = true;
      $wgGroupPermissions['sysop']['editwidgets'] = true;
      # 1 GB ought to be enough for everyone
      $wgUploadSizeWarning = 1024*1024*512;
      $wgMaxUploadSize = 1024*1024*1024;

      $wgEnableEmail = true;
      $wgPasswordSender = "wiki@fediversity.eu";
      $wgEmergencyContact = "wiki@fediversity.eu";
      $wgSMTP = [
        'host'      => 'mail.protagio.nl',
        'IDHost'    => 'fediversity.eu',
        'localhost' => 'fediversity.eu',
        'port'      => 587,
        'auth'      => true,
        'username'  => 'wiki@fediversity.eu',
      ];
      require_once("${config.age.secrets.wiki-smtp-password.path}");

      $wgHeadScriptCode = <<<'END'
      <link rel=me href="https://mastodon.fediversity.eu/@fediversity">
      END;
    '';

    extensions = {
      VisualEditor = null;
    };
  };

  age.secrets.wiki-smtp-password.owner = "mediawiki";

  services.nginx = {
    enable = true;
    virtualHosts."wiki.fediversity.eu" = {
      basicAuthFile = config.age.secrets.wiki-basicauth-htpasswd.path;
      forceSSL = true;
      enableACME = true;
    };
  };

  age.secrets.wiki-basicauth-htpasswd.owner = "nginx";

  security.acme = {
    acceptTerms = true;
    defaults.email = "systeemmail@procolix.com";
  };

  users.users.nginx.extraGroups = [ "acme" ];
}
