---
# roles/config-virt/tasks/main.yml

- name: Check to see if we already have a uvtool image
  find:
    path: "/var/lib/uvtool/libvirt/images"
    patterns: "x-uvt-b64-*"
  register: uvtool_image

- name: Get ubuntu image for uvtool
  when: "{{ uvtool_image.matched < 1 }}"
  command: uvt-simplestreams-libvirt sync --source http://cloud-images.ubuntu.com/daily \
    release={{ ansible_distribution_release }} arch=amd64
  args:
    creates: "/var/lib/uvtool/libvirt/images/x-uvt-b64-*"
  async: 1200
  poll: 0
  register: uvt_sync

- name: collect libvirt network facts
  virt_net:
    command=facts

- name: Tear down libvirt's default network
  when: not on_maas and ansible_libvirt_networks["default"] is defined
  virt_net:
    command={{ item }}
    name=default
  with_items:
    - destroy
    - undefine

# note, this isn't idempotent, so may need manual fixing if it changes
- name: define libvirt networks IP/DHCP/DNS settings
  when: not on_maas
  virt_net:
    name=xos-{{ item.name }}
    command=define
    xml='{{ lookup("template", "virt_net.xml.j2") }}'
  with_items: '{{ virt_nets }}'

- name: collect libvirt network facts after defining new network
  when: not on_maas
  virt_net:
    command=facts

- name: start libvirt networks
  when: not on_maas and ansible_libvirt_networks["xos-{{ item.name }}"].state != "active"
  virt_net:
    name=xos-{{ item.name }}
    command=create
  with_items: '{{ virt_nets }}'

- name: have libvirt networks autostart
  when: not on_maas and ansible_libvirt_networks["xos-{{ item.name }}"].autostart != "yes"
  virt_net:
    name=xos-{{ item.name }}
    autostart=yes
  with_items: '{{ virt_nets }}'


- name: Have libvirt enable port forwarding to VM's
  become: yes
  template:
    src={{ item }}.j2
    dest=/etc/libvirt/hooks/{{ item }}
    mode=0755 owner=root
  with_items:
    - daemon
    - qemu
  notify:
    - reload libvirt-bin
    - run qemu hook
  when: not on_maas

- name: Wait for uvt-kvm image to be available
  when: "{{ uvtool_image.matched < 1 }}"
  async_status: jid={{ uvt_sync.ansible_job_id }}
  register: uvt_sync_result
  until: uvt_sync_result.finished
  delay: 10
  retries: 120
