---

# item 1 is machine info
# item 0 is robot info

- name: "Set the machine and robot info"
  set_fact:
    machine_info: '{{ item.1 }}'
    robot_info: '{{ item.0 }}'

- name: "Check if profile {{ machine_info.name }}-{{ robot_info.name }} exists"
  command: "docker exec cobbler cobbler profile find --name={{ machine_info.name }}-{{ robot_info.name }}"
  register: profile_state
  changed_when: False

- name: "Calculate total number of hosts in this robot"
  set_fact:
    total_machines: '{{ robot_info.visionCount + robot_info.operatorCount + 1 }}'

- name: "Determine the robot has operator"
  set_fact:
    robot_has_operator: '{{ robot_info.operatorCount }}'

- name: "Render the preseed file {{ machine_info.kickstartTemplate }} to /etc/docker-compose/cobbler/dist"
  template:
    src: "{{ machine_info.kickstartTemplate }}"
    dest: "/etc/docker-compose/cobbler/dist/{{ machine_info.name }}-{{ robot_info.name }}.seed"
  register: preseed_state

- name: "Copy the preseed file to cobbler's /var/lib/cobbler/kickstarts/ location"
  command: "docker exec cobbler cp /dist/{{ machine_info.name }}-{{ robot_info.name }}.seed /var/lib/cobbler/kickstarts/"

- name: "Add the profile {{ machine_info.name }}-{{ robot_info.name }}"
  command: "docker exec cobbler cobbler profile add
    --name {{ machine_info.name }}-{{ robot_info.name }}
    --distro {{ machine_info.distro }}
    --kickstart /var/lib/cobbler/kickstarts/{{ machine_info.name }}-{{ robot_info.name }}.seed"
  when: profile_state.stdout == ""

- name: "Update the profile {{ machine_info.name }}-{{ robot_info.name }}"
  command: "docker exec cobbler cobbler profile edit
    --name {{ machine_info.name }}-{{ robot_info.name }}
    --distro {{ machine_info.distro }}
    --kickstart /var/lib/cobbler/kickstarts/{{ machine_info.name }}-{{ robot_info.name }}.seed"
  when: profile_state.stdout != "" and preseed_state.changed
