# platform = multi_platform_debian,multi_platform_fedora,multi_platform_ol,multi_platform_rhel,multi_platform_rhv,multi_platform_sle,multi_platform_slmicro,multi_platform_almalinux
# reboot = true
# strategy = restrict
# complexity = medium
# disruption = low



- name: Check random.trust_cpu argument exists
  ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*random.trust_cpu=' /etc/default/grub
  check_mode: False
  failed_when: False
  changed_when: False
  register: argcheck

- name: Check random.trust_cpu argument exists
  ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
  check_mode: False
  failed_when: False
  changed_when: False
  register: linecheck

- name: Add random.trust_cpu argument
  ansible.builtin.lineinfile:
    line: 'GRUB_CMDLINE_LINUX="random.trust_cpu=on "'
    state: present
    dest: /etc/default/grub
    create: yes
    mode: '0644'
  when: argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and linecheck.rc != 0

- name: Replace existing random.trust_cpu argument
  ansible.builtin.replace:
      path: /etc/default/grub
      regexp: 'random.trust_cpu=[a-zA-Z0-9,]+'
      replace: 'random.trust_cpu=on'
  when: argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and linecheck.rc == 0

- name: Add random.trust_cpu argument
  ansible.builtin.replace:
      path: /etc/default/grub
      regexp: '(^\s*GRUB_CMDLINE_LINUX=.*)"'
      replace: '\1 random.trust_cpu=on"'
  when: argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and linecheck.rc == 0


- name: Check if random.trust_cpu argument is already present in /etc/default/grub
  ansible.builtin.slurp:
    src: /etc/default/grub
  register: etc_default_grub

- name: Check if random.trust_cpu argument is already present
  ansible.builtin.command: /sbin/grubby --info=ALL
  register: grubby_info
  check_mode: False
  changed_when: False
  failed_when: False

- name: Update grub defaults and the bootloader menu
  ansible.builtin.command: /sbin/grubby --update-kernel=ALL --args="random.trust_cpu=on"
  when: (grubby_info.stdout is not search('random.trust_cpu=on')) or ((etc_default_grub['content'] | b64decode) is not search('random.trust_cpu=on'))

