- name: enable {{plugin_key}} nextcloud plugin
  command: "{{nextcloud_docker_exec_occ}} app:enable {{plugin_key}}"
  register: enable_result
  changed_when: enable_result.rc == 0 and ("already enabled" not in enable_result.stdout)

- name: Check if {{nextcloud_control_node_plugin_vars_directory}}{{ plugin_key }}.yml exists
  stat:
    path: "{{nextcloud_control_node_plugin_vars_directory}}{{ plugin_key }}.yml"
  delegate_to: localhost
  become: false
  register: plugin_vars_file

- name: "Load {{ plugin_key }} configuration variables"
  include_vars:
    file: "{{nextcloud_control_node_plugin_vars_directory}}{{ plugin_key }}.yml"
  when: plugin_vars_file.stat.exists

- name: "Set plugin configuration (batched shell, no async)"
  ansible.builtin.shell: |
    set -euo pipefail
    {% for item in (plugin_configuration | default([])) %}
    {{ nextcloud_docker_exec_occ }} \
      config:app:set {{ item.appid }} {{ item.configkey }} \
      --value '{{ ( (item.configvalue | to_json) if (item.configvalue is mapping) else (item.configvalue | string) ) 
            | regex_replace("'", "'" ~ '"' ~ "'" ~ '"' ~ "'") }}'
    {% endfor %}
  args:
    executable: /bin/bash
  when: plugin_vars_file.stat.exists
  register: config_set_shell
  changed_when: >
    not ASYNC_ENABLED and
    (config_set_shell.stdout | default('')) is search(' set to ')
  failed_when: not ASYNC_ENABLED and config_set_shell.rc != 0
  async: "{{ ASYNC_TIME if ASYNC_ENABLED | bool else omit }}"
  poll:  "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}"

- name: Check if {{nextcloud_control_node_plugin_tasks_directory}}{{ plugin_key }}.yml exists
  stat:
    path: "{{nextcloud_control_node_plugin_tasks_directory}}{{ plugin_key }}.yml"
  delegate_to: localhost
  become: false
  register: plugin_tasks_file

- name: "include {{nextcloud_control_node_plugin_tasks_directory}}{{ plugin_key }}.yml"
  include_tasks: "{{nextcloud_control_node_plugin_tasks_directory}}{{ plugin_key }}.yml"
  when: plugin_tasks_file.stat.exists