---
- name: Ensure that the download and install dirs exist
  file: path={{ item }} state=directory
  with_items:
    - '{{ mw_download_dir }}'
    - '{{ mw_install_dir }}'
  tags: mediawiki
  
- name: Download the mediawiki tar file
  get_url: url={{ mw_download_url }} dest={{ mw_download_dir }}
  when:
    - not mw_install_from_package
    - mw_install_from_tar
  tags: mediawiki

- name: Unpack the mediawiki tar file
  unarchive: copy=no src={{ mw_download_dir }}/mediawiki-{{ mw_version }}.{{ mw_minor_minor }}.tar.gz dest={{ mw_download_dir }}
  args:
    creates: '{{ mw_download_dir }}/mediawiki-{{ mw_version }}.{{ mw_minor_minor }}/INSTALL'
  when: mw_install_from_tar
  tags: mediawiki

- name: Move the mediawiki files to the right place
  command: cp -a {{ mw_download_dir }}/mediawiki-{{ mw_version }}.{{ mw_minor_minor }} {{ mw_doc_root }}
  args:
    creates: '{{ mw_doc_root }}/index.php'
  when: mw_install_from_tar
  tags: mediawiki

- name: Create the images subdirs
  file: dest={{ mw_doc_root }}/images/{{ item }} state=directory
  with_items: '{{ mw_upload_subdirs }}'
  tags: mediawiki

- name: Set the correct ownership of the mediawiki files
  file: dest={{ mw_doc_root }} owner={{ item.user }} group={{ item.group }} recurse=yes state=directory
  with_items: '{{ phpfpm_pools }}'
  tags: mediawiki

- name: Create the mediawiki conf dir
  file: path={{ mw_conf_dir }} state=directory
  tags: mediawiki

- block:

  - name: Check if the mediawiki instance has been initialized already
    stat: path={{ mw_doc_root }}/.mwinitialized
    register: mw_init

  tags: [ 'mediawiki', 'mediawiki_init' ]

- block:
  - name: Create a file with the DB password
    copy: src=mw_db_passwd.j2 dest=/tmp/mw_db_passwd owner=root group=root mode=0400

  - name: Create a file with the admin password
    copy: src=mw_admin_passwd.j2 dest=/tmp/mw_admin_passwd owner=root group=root mode=0400

  - name: Initialize the mediawiki instance
    shell: cd {{ mw_doc_root }} ; php maintenance/install.php --confpath {{ mw_conf_dir }} --dbname {{ mw_db_name }} --dbprefix {{ mw_db_table_prefix }} --dbuser {{ mw_db_user }} --dbpassfile /tmp/mw_db_passwd --with-extensions --scriptpath {{ mw_uri }} --passfile /tmp/mw_admin_passwd --wiki {{ mw_id }} --dbserver {{ mw_db_host }} --dbtype mysql --server https://{{ mw_wiki_servername }} "{{ mw_wiki_name }}" {{ mw_system_user }} && touch {{ mw_doc_root }}/.mwinitialized ; rm -f /tmp/mw_db_passwd /tmp/mw_admin_passwd
    args:
      creates: '{{ mw_doc_root }}/.mwinitialized'

  when: mw_init.stat.exists is defined and not mw_init.stat.exists
  tags: [ 'mediawiki', 'mediawiki_init' ]