# SPDX-License-Identifier: MIT
---
# yamllint disable rule:line-length
- name: Set platform/version specific variables
  include_vars: "{{ item }}"
  loop:
    - "{{ role_path }}/vars/default.yml"
    - "{{ role_path }}/vars/{{ ansible_facts['os_family'] }}.yml"
    - "{{ role_path }}/vars/{{ ansible_facts['distribution'] }}.yml"
    - "{{ role_path }}/vars/{{ ansible_facts['distribution'] }}_{{ ansible_facts['distribution_major_version'] }}.yml"
    - "{{ role_path }}/vars/{{ ansible_facts['distribution'] }}_{{ ansible_facts['distribution_version'] }}.yml"
  when: item is file
# yamllint enable rule:line-length

- name: Determine if system is ostree and set flag
  when: not __ansible_pcp_is_ostree is defined
  block:
    - name: Check if system is ostree
      stat:
        path: /run/ostree-booted
      register: __ostree_booted_stat

    - name: Set flag to indicate system is ostree
      set_fact:
        __ansible_pcp_is_ostree: "{{ __ostree_booted_stat.stat.exists }}"

- name: Determine if host is booted
  when: __pcp_is_booted is not defined
  block:
    - name: Run systemctl
      # noqa command-instead-of-module
      command: systemctl is-system-running
      register: __is_system_running
      changed_when: false
      check_mode: false
      failed_when: false

    - name: Require installed systemd
      fail:
        msg: "Error: This role requires systemd to be installed."
      when: '"No such file or directory" in __is_system_running.msg | d("")'

    - name: Set flag to indicate that systemd runtime operations are available
      set_fact:
        __pcp_is_booted: "{{ __is_system_running.stdout != 'offline' }}"

- name: Install Performance Co-Pilot packages
  package:
    name: "{{ __pcp_packages + __pcp_packages_extra + pcp_optional_packages }}"
    state: present
    use: "{{ (__ansible_pcp_is_ostree | d(false)) |
             ternary('ansible.posix.rhel_rpm_ostree', omit) }}"

- name: Install authentication packages
  package:
    name: "{{ __pcp_sasl_packages }}"
    state: present
    use: "{{ (__ansible_pcp_is_ostree | d(false)) |
             ternary('ansible.posix.rhel_rpm_ostree', omit) }}"
  when:
    - __pcp_sasl_packages | d([]) | length > 0
    - pcp_accounts | d([]) | length > 0

- name: Include pmcd
  include_tasks: pmcd.yml

- name: Include pmie
  include_tasks: pmie.yml

- name: Include pmlogger
  include_tasks: pmlogger.yml

- name: Include pmproxy
  include_tasks: pmproxy.yml
  when: pcp_rest_api | d(false) | bool
