# SPDX-License-Identifier: MIT
---
- name: Configure resource primitive {{ resource.id }}
  command:
    # pcs supports only one set of attributes, that's the reason for
    # *_attrs[0] instead of looping over *_attrs
    cmd: >
      pcs -f {{ __ha_cluster_tempfile_cib_xml.path | quote }}
      {%
        if not resource_is_stonith
        and not resource.copy_operations_from_agent | d(true)
      %}
        --no-default-ops
      {% endif %}
      --
      {% if resource_is_stonith %} stonith {% else %} resource {% endif %}
      create {{ resource.id | quote }}
      {% if resource_is_stonith %}
        {{ resource.agent | replace("stonith:", "") | quote }}
      {% else %}
        {{ resource.agent | quote }}
      {% endif %}

      {% if resource.instance_attrs[0].attrs | d([]) %}
        {% for attr in resource.instance_attrs[0].attrs %}
          {{ attr.name | quote }}={{ attr.value | quote }}
        {% endfor %}
      {% endif %}

      {% if resource.meta_attrs[0].attrs | d([]) %}
        meta
        {% for attr in resource.meta_attrs[0].attrs %}
          {{ attr.name | quote }}={{ attr.value | quote }}
        {% endfor %}
      {% endif %}

      {% if resource.operations | d([]) %}
        {% for operation in resource.operations %}
          op
          {% if operation.action is defined %}
            {{ operation.action | quote }}
          {% endif %}
          {% if operation.attrs | d([]) %}
            {% for attr in operation.attrs %}
              {{ attr.name | quote }}={{ attr.value | quote }}
            {% endfor %}
          {% endif %}
        {% endfor %}
      {% endif %}

      {% if __ha_cluster_primitive_bundle_map[resource.id] | d() %}
        bundle {{ __ha_cluster_primitive_bundle_map[resource.id] | quote }}
      {% endif %}
  # We always need to create CIB to see whether it's the same as what is
  # already present in the cluster. However, we don't want to report it as a
  # change since the only thing which matters is pushing the resulting CIB to
  # the cluster.
  check_mode: false
  changed_when: not ansible_check_mode

- name: Configure utilization for resource primitive {{ resource.id }}
  command:
    # Multiple sets of utilization per node are not supported by pcs (and
    # therefore the role) as of yet
    cmd: >
      pcs -f {{ __ha_cluster_tempfile_cib_xml.path | quote }}
      -- resource utilization {{ resource.id | quote }}
      {% for attr in resource.utilization[0].attrs | d([]) %}
        {{ attr.name | quote }}={{ attr.value | quote }}
      {% endfor %}
  # We always need to create CIB to see whether it's the same as what is
  # already present in the cluster. However, we don't want to report it as a
  # change since the only thing which matters is pushing the resulting CIB to
  # the cluster.
  check_mode: false
  changed_when: not ansible_check_mode
  when:
    - resource.utilization | d([]) | length > 0
