---

- name: "Check if distro {{ item.name }}-{{ item.arch }} exists"
  command: "docker exec cobbler cobbler distro find --name={{ item.name }}-{{ item.arch }}"
  register: distro_state
  changed_when: False

- name: "Download the image {{ item.name }}"
  get_url:
    url: "{{ item.url }}"
    dest: "/etc/docker-compose/cobbler/isos/{{ item.name }}.iso"
  when: distro_state.stdout == ""

- name: "Mount the image {{ item.name }} to /etc/docker-compose/cobbler/dist/image"
  mount:
    src: "/etc/docker-compose/cobbler/isos/{{ item.name }}.iso"
    name: "/etc/docker-compose/cobbler/dist/image"
    fstype: iso9660
    opts: loop,ro
    state: mounted
  when: distro_state.stdout == ""

- name: restart the cobbler container
  docker_service:
    project_src: /etc/docker-compose/cobbler
    state: present
    restarted: yes
  when: distro_state.stdout == ""

- name: "Import image {{ item.name }} into clobber"
  command: "docker exec cobbler cobbler import
    --name={{ item.name }}
    --breed={{ item.breed }}
    --arch={{ item.arch }}
    --path=/dist/image"
  register: item_image_import_result
  retries: 2
  delay: 10
  until: item_image_import_result|succeeded
  when: distro_state.stdout == ""

- name: "Unmount the image {{ item.name }} from /etc/docker-compose/cobbler/dist/image"
  mount:
    name: "/etc/docker-compose/cobbler/dist/image"
    state: unmounted
  when: distro_state.stdout == ""
