# SPDX-License-Identifier: MIT
---
# Verify if resource_clone exists
- name: Verify resource_clone presence {{ resource_clone.resource_id }}
  ansible.builtin.command:
    cmd: >-
      crm -c {{ __ha_cluster_crm_shadow }}
      configure show {{ resource_clone.resource_id }}
  register: __ha_cluster_constraint_resource
  changed_when: false
  failed_when:
    - "'does not exist' in __ha_cluster_constraint_resource.stderr"

- name: Define resource clone resource_clone.id '{{
    resource_clone.id | d('cln_' + resource_clone.resource_id) }}'
  ansible.builtin.set_fact:
    __ha_cluster_resource_id:
      "{{ resource_clone.id if resource_clone.id is defined
        else 'cln_' + resource_clone.resource_id | quote }}"

# Verify if Shadow CIB already contains same resource id.
- name: Verify resource clone presence {{ __ha_cluster_resource_id }}
  ansible.builtin.command:
    cmd: >-
      crm -c {{ __ha_cluster_crm_shadow }}
      configure show {{ __ha_cluster_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 clone {{ __ha_cluster_resource_id }}
  ansible.builtin.command:
    cmd: >-
      crm --force -c {{ __ha_cluster_crm_shadow }}
      configure delete {{ __ha_cluster_resource_id }}
  when: __ha_cluster_resource_status.rc == 0
  check_mode: false
  changed_when: not ansible_check_mode


# Clone is default resource type, unless attribute ms: true is specified
# Pacemaker 2.0 deprecated use of ms, but it is still valid and supported
# solution for SAP Hana clusters on SUSE using SAPHanaSR.

# Yes command will skip all prompts, resulting in rc>0
# exit $? reveals return code of crm, which is masked by yes
- name: Configure resource clone {{ __ha_cluster_resource_id }}
  ansible.builtin.shell:
    cmd: |
      yes 'n' | crm -c {{ __ha_cluster_crm_shadow }} configure \
      {% if resource_clone.ms is defined and resource_clone.ms %}
        ms {% else %} clone {% endif %} \
      {{ __ha_cluster_resource_id }} \
      {{ resource_clone.resource_id | quote }} \
      {% if resource_clone.meta_attrs[0].attrs | default(False) %}
        meta {% for attr in resource_clone.meta_attrs[0].attrs -%}
          {{ attr.name | quote }}={{ attr.value | quote }} \
        {% 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
