# SPDX-License-Identifier: MIT
---
# Verify if Shadow CIB already contains same resource id.
- name: Verify resource primitive presence {{ resource.id }}
  ansible.builtin.command:
    cmd: crm -c {{ __ha_cluster_crm_shadow }} configure show {{ resource.id }}
  register: __ha_cluster_resource_status
  changed_when: false
  failed_when: false

# Delete resource id in Shadow CIB to avoid errors during cibadmin patch.
- name: Delete present resource primitive {{ resource.id }}
  ansible.builtin.command:
    cmd: >-
      crm --force -c {{ __ha_cluster_crm_shadow }}
      configure delete {{ resource.id }}
  when: __ha_cluster_resource_status.rc == 0
  check_mode: false
  changed_when: not ansible_check_mode


# Yes command will skip all prompts, resulting in rc>0
# exit $? reveals return code of crm, which is masked by yes
- name: Configure resource primitive {{ resource.id }}
  ansible.builtin.shell:  # noqa jinja[spacing]
    cmd: |
      yes 'n' | crm -c {{ __ha_cluster_crm_shadow }} configure primitive \
        {{ resource.id | quote }} {{ resource.agent | quote }} \
      {% if resource.instance_attrs is defined
        and resource.instance_attrs | type_debug == 'list'
        and resource.instance_attrs[0].attrs is defined
        and resource.instance_attrs[0].attrs | type_debug == 'list' %}
        params {% for attr in resource.instance_attrs[0].attrs -%}
          {{ attr.name | quote }}={{ attr.value | quote }} \
        {% endfor %}
      {% endif %}
      {% if resource.meta_attrs is defined
        and resource.meta_attrs | type_debug == 'list'
        and resource.meta_attrs[0].attrs is defined
        and resource.meta_attrs[0].attrs | type_debug == 'list' %}
        meta {% for attr in resource.meta_attrs[0].attrs -%}
          {{ attr.name | quote }}={{ attr.value | quote }} \
        {% endfor %}
      {% endif %}
      {% if resource.operations is defined
        and resource.operations | type_debug == 'list' %}\
        {% for operation in resource.operations %}
          {% if operation.action is defined
            and operation.attrs is defined
            and operation.attrs | type_debug == 'list' %}
            op {{ operation.action | quote }} \
            {%- for attr in operation.attrs -%}
              {{ attr.name | quote }}={{ attr.value | quote }} \
            {% endfor %}
          {% endif %}
        {% endfor %}
      {% endif %}
      ;exit $?
  check_mode: false
  changed_when: not ansible_check_mode
  ignore_errors: true
  register: __ha_cluster_crmsh_output


- name: Display crm command error details
  ansible.builtin.fail:
    msg:
      - "{{ __ha_cluster_crmsh_output.stderr_lines }}"
      - "{{ __ha_cluster_crmsh_output.stdout_lines }}"
  when:
    - __ha_cluster_crmsh_output is defined
    - __ha_cluster_crmsh_output.rc != 0
