---
- name: "include docker-central-database"
  include_role: 
    name: docker-central-database

- name: "create {{ nextcloud_host_config_additives_directory }}"
  file:
    path: "{{ nextcloud_host_config_additives_directory }}"
    state: directory
    mode: 0755

- name: "Create config files at {{ nextcloud_host_config_additives_directory }}"
  template:
    src:    "{{ item }}"
    dest:   "{{ nextcloud_host_config_additives_directory }}/{{ item | basename | regex_replace('\\.j2$', '') }}"
    owner:  "{{nextcloud_docker_user_id}}"
    group:  "{{nextcloud_docker_user_id}}"
  loop:     "{{ lookup('fileglob', role_path ~ '/templates/config/*.j2', wantlist=True) }}"
  # Not all type of changes take instantly place. Due to this reason a rebuild is required.
  notify: docker compose project setup

- name: "include role for {{application_id}} to receive certs & do modification routines"
  include_role:
    name: nginx-https-get-cert-modify-all

- name: create nextcloud nginx proxy configuration file
  template: 
    src:  "nginx/host.conf.j2" 
    dest: "{{nginx.directories.http.servers}}{{domains | get_domain(application_id)}}.conf"
  notify: restart nginx

- name: create internal nextcloud nginx configuration
  template: 
    src:  "nginx/docker.conf.j2" 
    dest: "{{docker_compose.directories.volumes}}nginx.conf"
  notify: restart nextcloud nginx service

- include_tasks: "{{ playbook_dir }}/roles/docker-compose/tasks/create-files.yml"

- name: Flush all handlers immediately so that occ can be used
  meta: flush_handlers

- name: Setup config.php 
  include_tasks: config.yml

- name: Setup Nextcloud Plugins
  include_tasks: plugin.yml
  loop: "{{applications[application_id].plugins | dict2items }}"
  loop_control:
    loop_var: plugin_item
  vars:
    plugin_key:   "{{ plugin_item.key }}"
    plugin_value: "{{ plugin_item.value }}"

- name: Load system configuration
  include_tasks: system.yml

- name: Add missing database indices in Nextcloud
  command: >
    {{nextcloud_docker_exec_occ}} db:add-missing-indices
  register: db_indices_result
  changed_when: >
    'Adding additional' in db_indices_result.stdout or 
    'Removing' in db_indices_result.stdout or 
    'updated successfully' in db_indices_result.stdout
  failed_when: db_indices_result.rc != 0
