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

- name: Define ticket constraint.id {{ constraint.id | d(constraint_index) }}
  ansible.builtin.set_fact:
    __ha_cluster_constraint_id:
      "{{ constraint.id if constraint.id is defined else
      'tck_' + (constraint.resource.id | quote) }}"

# Verify if Shadow CIB already contains same constraint id.
- name: Verify ticket constraint presence {{ __ha_cluster_constraint_id }}
  ansible.builtin.command:
    cmd: >-
      crm -c {{ __ha_cluster_crm_shadow }}
      configure show {{ __ha_cluster_constraint_id }}
  register: __ha_cluster_constraint_status
  changed_when: false
  failed_when: false

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

# Expect module is used to combat crmsh freezing when asking for user input
- name: Configure ticket constraint {{ __ha_cluster_constraint_id }}
  ansible.builtin.expect:
    command: |
      crm -c {{ __ha_cluster_crm_shadow }}
      configure rsc_ticket {{ __ha_cluster_constraint_id }}
      {{ constraint.ticket | quote }}:
      {% if constraint.resource.role | d() and
        constraint.resource.role | lower in __ha_cluster_crmsh_roles %}
        {{ constraint.resource.id | quote }}:{{
          constraint.resource.role | lower | capitalize | quote }}
      {% else %}
        {{ constraint.resource.id | quote }}
      {% endif %}
      {% for option in constraint.options | d([]) %}
        {{ option.name | quote }}={{ option.value | quote }}
      {% endfor %}
    # ERROR and "Do you still want to commit (y/n)?" trigger response "n".
    responses:
      ".*ERROR.*": "n"
      ".*y/n*": "n"
  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.stdout_lines }}"
  when:
    - __ha_cluster_crmsh_output is defined
    - __ha_cluster_crmsh_output.rc != 0
