---

- name: Get global preferences
  command: php occ config:list --private --output=json
  args:
    chdir: "{{ nextcloud_installation_dir }}"
  register: _result
  changed_when: false
  no_log: true
  become: true
  become_user: "{{ nextcloud_file_owner }}"

- name: Parse global preferences as json and merge configurations
  set_fact:
    _nextcloud_old_preferences:
      "{{ _result.stdout | from_json }}"
    _nextcloud_updated_preferences: >-
      {{
        _result.stdout | from_json | combine(nextcloud_config, recursive=True)
      }}
  no_log: true

- name: Configure nextcloud and apps
  block:
    - name: Create temporary config file
      tempfile:
        suffix: nextcloud
      register: _result

    - name: Save config to file
      copy:
        content: "{{ nextcloud_config | to_json }}"
        dest: "{{ _result.path }}"
        owner: "{{ nextcloud_file_owner }}"
        mode: 0o400

    - name: Set up global preferences
      command: php occ config:import "{{ _result.path }}"
      args:
        chdir: "{{ nextcloud_installation_dir }}"
      become: true
      become_user: "{{ nextcloud_file_owner }}"
      register: result
      changed_when: result is success
      notify: nextcloud update htaccess
      failed_when: (result.stdout is not search('successfully imported')
        or result is failed)

    - meta: flush_handlers

    - name: Delete temporary config file
      file:
        path: "{{ _result.path }}"
        state: absent
  when: _nextcloud_updated_preferences != _nextcloud_old_preferences