# 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: Establish bpftrace package names
  set_fact:
    __bpftrace_packages_extra: "{{ __bpftrace_packages +
                                __bpftrace_packages_extra }}"
  when:
    - bpftrace_metrics_provider == 'pcp'
    - __bpftrace_packages_pcp | d([]) | length > 0

- name: Establish bpftrace metrics package names
  set_fact:
    __bpftrace_packages_extra: "{{ __bpftrace_packages_pcp +
                                __bpftrace_packages_extra }}"
  when:
    - bpftrace_metrics_provider == 'pcp'
    - __bpftrace_packages_pcp | d([]) | length > 0

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

- name: Extract allowed bpftrace user accounts
  set_fact:
    __bpftrace_usernames: "{{ __bpftrace_usernames }},{{ item.user }}"
  when: item.user is defined
  with_items: "{{ bpftrace_users }}"

- name: Ensure PCP bpftrace configuration directory exists
  file:
    path: "{{ __bpftrace_conf_dir }}"
    state: directory
    mode: "0755"
  when: bpftrace_metrics_provider == 'pcp'

- name: Ensure PCP bpftrace agent is configured
  template:
    src: bpftrace.conf.j2
    dest: "{{ __bpftrace_conf }}"
    mode: "0600"
    follow: true
  when: bpftrace_metrics_provider == 'pcp'
