---

- name: Read cpuinfo from kernel
  ansible.builtin.command:
    cmd: cat /proc/cpuinfo
  register: cpu_info
  changed_when: false

- name: Verify if Intel VMX or AMD SVM is enabled
  ansible.builtin.fail:
    msg: "Intel VMX or AMD SVE not enabled"
  when: "'vmx' not in cpu_info.stdout and 'svm' not in cpu_info.stdout"

- name: Include OS-specific variables
  ansible.builtin.include_vars: "{{ ansible_os_family }}.yml"

- name: Add virt-manager to list of kvm packages
  ansible.builtin.set_fact:
    kvm_package_names: "{{ kvm_package_names + kvm_vm_manager_package_names }}"
  when: kvm_virtual_machine_manager

- name: Install kvm packages
  ansible.builtin.package:
    name: "{{ item }}"
    state: present
  with_items:
  - "{{ kvm_package_names }}"

- name: Load and persist kernel module "kvm_amd"
  when: cpu_info.stdout.find('sev') != -1
  block:
  - name: Load kernel module "kvm_amd" temporarily
    community.general.modprobe:
      name: "kvm_amd"
      params: "sev=1"
      state: present
  - name: Load kernel module "kvm_amd" persistently
    ansible.builtin.template:
      src: "etc/modules-load.d/10-amd-sve.conf.j2"
      dest: "/etc/modules-load.d/10-amd-sve.conf"
      owner: root
      group: root
      mode: "0644"

- name: Append unix user to unix groups to interact with qemu/kvm
  ansible.builtin.user:
    name: "{{ item.name }}"
    append: true
    groups: "{{ kvm_unix_groups }}"
  with_items: "{{ kvm_users }}"

- name: Start and enable {{ kvm_service_name }}
  ansible.builtin.systemd:
    name: "{{ kvm_service_name }}"
    state: started
    enabled: true

# FIXME:
# Create btrfs subvolume /var/lib/libvirt/images and execute `chattr +C` if subvolume was successfullt created. Check if
# directory exists. If not check if filesystem type of /var/lib/libvirt/images is btrfs via `stat -f --format=%T <path>`
# and if the inode is 256 or 2 with `stat --format="%i" <path>`.

# - name: ...