# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

---

- name: Check if KVM is installed
  shell: |
    RESULTS=$(apt list -qq qemu-kvm --installed 2>/dev/null) # ignore errors, stdout is the only thing we care about
    if [ -z "${RESULTS}" ]; then
      # results are empty, the package does NOT exist
      exit 1
    fi
  args:
    executable: /bin/bash
  ignore_errors: true
  register: kvm_check
  changed_when: "kvm_check.rc > 0"
  tags:
    - kvm-install
    - kvm-packages

- name: Install kvm dependencies
  apt:
    pkg:
    - jq
    - uml-utilities
    - qemu-kvm
    - bridge-utils
    - virtinst
    - libvirt-daemon
    - libvirt-daemon-system
    - libvirt-clients
    update_cache: yes
  when: kvm_check.rc > 0
  tags:
    - kvm-install
    - kvm-packages

# TODO: Refactor timeout
- name: Reset ssh if KVM dependencies are active
  meta: reset_connection
  when: kvm_check.rc > 0
  tags:
    - kvm-install
    - kvm-packages

- name: Verify libvirtd daemon is running
  service:
    name: libvirtd
    enabled: yes
  tags:
    - kvm-install
    - kvm-packages
    - kvm-setup

# - name: Ensure host is able to able to support KVM
#   command:
#     cmd: virt-host-validate qemu
#   ignore_errors: true # the guest support fails
#   tags:
#     - kvm-install
#     - kvm-packages
#     - kvm-setup

- name: Setup qemu permissions to allow for root since apparmor is down
  shell: |
    sed -i "s|#user = \"root\"|user=\"root\"|g" /etc/libvirt/qemu.conf
    sed -i "s|#group = \"root\"|group=\"root\"|g" /etc/libvirt/qemu.conf
    systemctl restart libvirtd
  args:
    executable: /bin/bash
  tags:
    - kvm-install
    - kvm-setup

- name: Ensure vhost_net is enabled
  command:
    cmd: modprobe vhost_net
  tags:
  - kvm-setup

- name: Create local system image folder
  file:
    # image_base_dir
    path: '{{ image_base_dir }}'
    state: directory
    mode: '0744'
