#
# Cookbook Name:: kosmos-mediawiki
# Recipe:: default
#
# The MIT License (MIT)
#
# Copyright:: 2019, Kosmos Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

include_recipe 'apt'
include_recipe 'ark'
include_recipe 'composer'

server_name = 'wiki.kosmos.org'

node.override['mediawiki']['version']         = "1.34.2"
node.override['mediawiki']['webdir']          = "#{node['mediawiki']['docroot_dir']}/mediawiki-#{node['mediawiki']['version']}"
node.override['mediawiki']['tarball']['name'] = "mediawiki-#{node['mediawiki']['version']}.tar.gz"
node.override['mediawiki']['tarball']['url']  = "https://releases.wikimedia.org/mediawiki/1.34/#{node['mediawiki']['tarball']['name']}"
node.override['mediawiki']['language_code']   = 'en'
node.override['mediawiki']['server_name']     = server_name
node.override['mediawiki']['site_name']       = 'Kosmos Wiki'
protocol = node.chef_environment == "development" ? "http" : "https"
node.override['mediawiki']['server']          = "#{protocol}://#{server_name}"
mysql_credentials = data_bag_item('credentials', 'mysql')
mediawiki_credentials = data_bag_item('credentials', 'mediawiki')

node.override['mediawiki']['db']['root_password'] = mysql_credentials["root_password"]
node.override['mediawiki']['db']['pass'] = mediawiki_credentials["db_pass"]

directory "#{node['mediawiki']['webdir']}/skins/common/images" do
  owner node['nginx']['user']
  group node['nginx']['group']
  recursive true
  mode 0750
end

cookbook_file "#{node['mediawiki']['webdir']}/skins/common/images/kosmos.png" do
  source 'kosmos.png'
  owner node['nginx']['user']
  group node['nginx']['group']
  mode 0640
end

directory "#{node['mediawiki']['webdir']}/.well-known/acme-challenge" do
  owner     node["nginx"]["user"]
  group     node["nginx"]["group"]
  recursive true
  action    :create
end

include_recipe "mediawiki"
include_recipe "kosmos-nginx"
include_recipe "mediawiki::nginx"

ssl_cert = "/etc/letsencrypt/live/wiki.kosmos.org/fullchain.pem"
ssl_key = "/etc/letsencrypt/live/wiki.kosmos.org/privkey.pem"
template "#{node['nginx']['dir']}/sites-available/#{server_name}" do
  source "nginx.conf.erb"
  variables(
    docroot:        node['mediawiki']['webdir'],
    server_name:    server_name,
    ssl_cert:       ssl_cert,
    ssl_key:        ssl_key
  )
  action :create
  notifies :reload, "service[nginx]", :delayed
end

# Legacy vhost
nginx_site 'mediawiki' do
  action :disable
end

nginx_site server_name do
  action :enable
end

nginx_certbot_site server_name

#
# Extensions
#

mediawiki_credentials = Chef::EncryptedDataBagItem.load('credentials', 'mediawiki')

#
# MediawikiHubot extension
#

# requires curl extension
if platform?('ubuntu') && node[:platform_version].to_f < 16.04
  package "php5-curl"
else
  package "php-curl"
end

ark "MediawikiHubot" do
  url "https://github.com/67P/mediawiki-hubot/archive/master.zip"
  path "#{node['mediawiki']['webdir']}/extensions/MediawikiHubot"
  creates "MediawikiHubot/MediawikiHubot.php"
  action :cherry_pick
end

hubot_credentials = Chef::EncryptedDataBagItem.load('credentials', 'hal8000_xmpp')
webhook_token = hubot_credentials['webhook_token']

template "#{node['mediawiki']['webdir']}/extensions/MediawikiHubot/DefaultConfig.php" do
  source "MediawikiHubot/DefaultConfig.php.erb"
  variables webhook_url: "#{node['mediawiki']['hubot_base_url']}/incoming/#{webhook_token}",
            room_name: node['mediawiki']['hubot_room'],
            wiki_url: node['mediawiki']['url']
end

if node["mediawiki"]["ldap_enabled"]
  # LDAP
  git "#{node['mediawiki']['webdir']}/extensions/PluggableAuth" do
    repository "https://github.com/wikimedia/mediawiki-extensions-PluggableAuth.git"
    revision "5.7"
    user node["nginx"]["user"]
    group node["nginx"]["group"]
    action :sync
  end

  git "#{node['mediawiki']['webdir']}/extensions/LDAPProvider" do
    repository "https://github.com/wikimedia/mediawiki-extensions-LDAPProvider.git"
    revision "1.0.3"
    user node["nginx"]["user"]
    group node["nginx"]["group"]
    action :sync
  end

  git "#{node['mediawiki']['webdir']}/extensions/LDAPAuthentication2" do
    repository "https://github.com/wikimedia/mediawiki-extensions-LDAPAuthentication2.git"
    revision "1.0.1"
    user node["nginx"]["user"]
    group node["nginx"]["group"]
    action :sync
  end

  package "php-ldap"

  ldap_domain = node['kosmos-dirsrv']['master_hostname']
  ldap_encryption_type = node.chef_environment == "development" ? "clear" : "tls"
  ldap_base = "ou=kosmos.org,cn=users,dc=kosmos,dc=org"
end

ruby_block "configuration" do
  block do
    file = Chef::Util::FileEdit.new("#{node['mediawiki']['webdir']}/LocalSettings.php")
    file.search_file_replace_line(%r{\$wgLogo\ =\ \"\$wgResourceBasePath\/resources\/assets\/wiki.png\";},
                                  "$wgLogo = \"$wgResourceBasePath/skins/common/images/kosmos.png\";")
    file.insert_line_if_no_match(/# Our config/,
                                 <<-EOF
# Our config
$wgGroupPermissions['*']['edit'] = false;
$wgGroupPermissions['team'] = $wgGroupPermissions['user'];
$wgGroupPermissions['user']['edit'] = true;
$wgGroupPermissions['user']['editsemiprotected'] = false;
$wgGroupPermissions['autoconfirmed']['editsemiprotected'] = false;
$wgGroupPermissions['team']['edit'] = true;
$wgGroupPermissions['team']['protect'] = true;
$wgGroupPermissions['team']['editsemiprotected'] = true;
$wgGroupPermissions['team']['editprotected'] = true;
$wgGroupPermissions['sysop']['edit'] = true;
$wgEnableUploads = true;
$wgFileExtensions = [ 'png', 'gif', 'jpg', 'jpeg', 'webp', 'svg' ];
// Parse large SVGs, so they can be thumbnailed without errors
// https://phabricator.wikimedia.org/T199737
// https://www.mediawiki.org/wiki/Manual:$wgSVGMetadataCutoff
$wgSVGMetadataCutoff = 20000000; // 20 MB

$wgExtraNamespaces[100] = "Feature";
$wgNamespacesWithSubpages[100] = true;
$wgExtraNamespaces[101] = "Feature_Talk";
# Only allow sysops to edit "Feature" namespace
$wgGroupPermissions['team']['editfeature'] = true;
$wgGroupPermissions['sysop']['editfeature'] = true;
$wgNamespaceProtection[100] = array( 'editfeature' );
$wgSMTP = array (
   'IDHost' => 'kosmos.org', //this is used to build the Message-ID mail header
   'host'   => 'localhost', //this is the outgoing mail server name (SMTP server)
   'port'   => 25, //this is the port used by the SMTP server
   'auth'   => false,  //in my case, authentication is not required by the mail server for outgoing mail
);
$wgPasswordReminderResendTime = 0;
$wgArticlePath = "/$1";
                                 EOF
                                )
    file.insert_line_if_no_match(/MediawikiHubot\.php/,
                                 "require_once \"$IP/extensions/MediawikiHubot/MediawikiHubot.php\";")

    file.insert_line_if_no_match(/Mermaid/,
                                 "wfLoadExtension( 'Mermaid' );")
    file.insert_line_if_no_match(/WikiEditor/,
                                 "wfLoadExtension( 'WikiEditor' );")
    file.insert_line_if_no_match(/Cite/,
                                 "wfLoadExtension( 'Cite' );")

    if node["mediawiki"]["ldap_enabled"]
      file.insert_line_if_no_match(/# LDAP config/,
                                 <<-EOF
# LDAP config
$LDAPProviderDomainConfigProvider = function()
{
    $config = [
        "#{server_name}" => [
            "connection" => [
                "server" => "#{ldap_domain}",
                "enctype" => "#{ldap_encryption_type}",
                "user" => "#{mediawiki_credentials['ldap_user']}",
                "pass" => "#{mediawiki_credentials['ldap_password']}",
                "basedn" => "#{ldap_base}",
                "groupbasedn" => "#{ldap_base}",
                "userbasedn" => "#{ldap_base}",
                "searchattribute" => "uid",
                "searchstring" => "cn=USER-NAME,#{ldap_base}",
                "usernameattribute" => "uid",
                "realnameattribute" => "cn",
                "emailattribute" => "mail"
            ]
        ]
    ];

    return new \\MediaWiki\\Extension\\LDAPProvider\\DomainConfigProvider\\InlinePHPArray( $config );
};
# $wgPluggableAuth_EnableLocalLogin = true; # allow local logins
# Override the text for the login button. The default is "Log In With PluggableAuth"
$wgPluggableAuth_ButtonLabel = 'Log in';
wfLoadExtension( 'LDAPProvider' );
wfLoadExtension( 'PluggableAuth' );
wfLoadExtension( 'LDAPAuthentication2' );
# Disable account creation page, since this is not possible to create an account
# when only LDAP login is enabled
$wgGroupPermissions['*']['createaccount'] = false;
$wgGroupPermissions['*']['autocreateaccount'] = true;
                                 EOF
                                 )

      file.write_file
    end
  end
end

#
# Composer dependencies
#

file "#{node['mediawiki']['webdir']}/composer.local.json" do
  requires = { "require": {
    "mediawiki/mermaid": "~1.0"
  }}.to_json
  content requires
  owner node['nginx']['user']
  group node['nginx']['group']
end

composer_project node['mediawiki']['webdir'] do
  dev false
  quiet true
  prefer_dist false
  user node['nginx']['user']
  group node['nginx']['group']
  action :install
end

# This does not perform changes when it has already been executed. Needed when
# adding a new extension, for example for LDAP support
execute "Run the database updater" do
  cwd node['mediawiki']['webdir']
  command "./maintenance/update.php --quick"
end

#
# Backup
#

unless node.chef_environment == "development"
  node.override["backup"]["mysql"]["host"] = "localhost"
  node.override["backup"]["mysql"]["username"] = "root"
  node.override["backup"]["mysql"]["password"] = node["mediawiki"]["db"]["root_password"]
  unless node["backup"]["mysql"]["databases"].include? 'mediawikidb'
    node.override["backup"]["mysql"]["databases"] =
      node["backup"]["mysql"]["databases"].to_a << "mediawikidb"
  end

  include_recipe "backup"
end
