# SPDX-License-Identifier: MIT
---
- name: Test for insights remediation enabled & disabled
  hosts: all
  gather_facts: false

  tasks:
    - name: Setup Insights
      import_tasks: tasks/setup_insights.yml

    - name: Ensure ansible_facts used by the test
      setup:
        gather_subset:
          - "!all"
          - "!min"
          - distribution_version

    - name: Skip if the RHEL version is older than 8.4
      meta: end_play
      when:
        - ansible_distribution_version is version("8.4", "<")

    - name: Test remediation
      block:
        - name: Register insights and enable remediation
          include_role:
            name: linux-system-roles.rhc
            public: true
          vars:
            rhc_auth:
              login:
                username: "{{ lsr_rhc_test_data.reg_username }}"
                password: "{{ lsr_rhc_test_data.reg_password }}"
            rhc_insights:
              remediation: present
              state: present
            rhc_organization: "{{ lsr_rhc_test_data.reg_organization }}"
            rhc_server:
              hostname: "{{ lsr_rhc_test_data.candlepin_host }}"
              port: "{{ lsr_rhc_test_data.candlepin_port }}"
              prefix: "{{ lsr_rhc_test_data.candlepin_prefix }}"
              insecure: "{{ lsr_rhc_test_data.candlepin_insecure }}"
            rhc_baseurl: "{{ lsr_rhc_test_data.baseurl | d(omit) }}"

        - name: Set the fact for the systemd service
          set_fact:
            yggdrasil_systemd_service: "{{ __rhc_yggdrasil_systemd_service + '.service' }}"

        - name: Get service_facts
          service_facts:

        - name: Check remediation is enabled
          assert:
            that:
              - yggdrasil_systemd_service in ansible_facts.services
              - ansible_facts.services[yggdrasil_systemd_service].status == 'enabled'

        - name: Disable remediation
          include_role:
            name: linux-system-roles.rhc
          vars:
            rhc_insights:
              remediation: absent

        - name: Get service_facts
          service_facts:

        - name: Check remediation is disabled
          assert:
            that:
              - yggdrasil_systemd_service in ansible_facts.services
              - ansible_facts.services[yggdrasil_systemd_service].status == 'disabled'

        - name: Disable remediation (noop)
          include_role:
            name: linux-system-roles.rhc
          vars:
            rhc_insights:
              remediation: absent

      always:
        - name: Unregister
          include_role:
            name: linux-system-roles.rhc
          vars:
            rhc_state: absent
