# SPDX-License-Identifier: MIT
---
# All required repositories are already part of SLES for SAP Applications.

# High Availability Extension (HAE) is required for cluster setup on SLES.
# All cluster packages are present on SLES_SAP and openSUSE,
# but not on base SLES without HAE.
- name: Block to assert that High Availability Extension is present on SLES
  when: ansible_distribution == 'SLES'
  block:

    - name: Query package sle-ha-release  # noqa command-instead-of-module
      ansible.builtin.command:
        cmd: rpm -q sle-ha-release
      register: __ha_cluster_sle_ha_release
      changed_when: false
      ignore_errors: true  # ignore and check /etc/products.d/ file instead

    - name: Check High Availability Extension presence using product file
      ansible.builtin.stat:
        path: /etc/products.d/sle-ha.prod
      register: __ha_cluster_sle_ha_stat
      when: __ha_cluster_sle_ha_release.rc != 0

    # Registering HA Extension results in:
    # - Created file /etc/products.d/sle-ha.prod
    # - Installed sle-ha-release package.
    # Cluster packages are not installed by default.
    - name: Assert that High Availability Extension is present
      ansible.builtin.assert:
        that:
          - __ha_cluster_sle_ha_release.rc == 0 or
            (__ha_cluster_sle_ha_stat is defined
              and __ha_cluster_sle_ha_stat.stat.exists)
        success_msg: "High Availability Extension was detected."
        fail_msg: |
          High Availability Extension is not registered!
          Register HA Extension before executing again.
      # Fatal fail will occur if any of cluster nodes is missing HAE
      any_errors_fatal: true


# Install zypper patterns before additional package installation
# Pattern installation will run only if pattern is not installed
# This ensures that command module shows correct changed status
- name: Query installed zypper patterns
  ansible.builtin.command:
    cmd: zypper patterns --installed-only
  register: __ha_cluster_installed_patterns
  changed_when: false
  ignore_errors: true

- name: Ensure that the required zypper patterns are installed
  ansible.builtin.command:
    cmd: zypper install -y -t pattern {{ item }}
  loop: "{{ (ha_cluster_zypper_patterns | list | d([])
    + __ha_cluster_zypper_patterns | list | d([])) | unique }}"
  # Retry added to handle post scripts problems like RC 107
  retries: 2
  delay: 10
  when: item not in __ha_cluster_installed_patterns.stdout
  changed_when: item not in __ha_cluster_installed_patterns.stdout
