- name: Install packages
  tags:
    - lxc-host
    - packages
  become: yes
  apt:
    name: "{{ items }}"
    install_recommends: no
  vars:
    items:
      - lxc
      - lxc-templates
      - debootstrap # For debian templates
      - python-lxc

#- debug:
#    msg: "item={{ item }}, host={{ host }}, lan={{ lan }}"
#  tags:
#    - lxc-host
#  with_dict: "{{ lxc_host__containers }}"
#  vars:
#    i: "{{ item }}"
#    host: "{{ host_database[item.key] }}"
#    lan: "{{ host_database | json_query(item.key + '.interfaces | * | [?role==`lan`]') | first }}"

- name: Configure host networking
  tags:
    - lxc-host
    - lxc-host-network
  include_tasks: networkd.yml

- name: List containers
  tags:
    - lxc-host
    - lxc-host-containers
  become: yes
  block:
    - name: Listing all containers
      shell: lxc-ls -1 -f -F NAME,STATE
      register: lxc_ls
      changed_when: False
    - set_fact:
        existing_containers_yaml: |
          {% for line in lxc_ls.stdout_lines[1:] %}
          {% set parts = line.split(" ") %}
          "{{ parts[0] }}":
            state: "{{ parts[1] }}"
          {% endfor %}
#"
    - set_fact:
        existing_containers: "{{ existing_containers_yaml | from_yaml }}"
    - set_fact:
        new_containers: "{{ lxc_host__containers | difference(existing_containers) }}"

- tags:
    - lxc-host
    - lxc-host-containers
  become: yes
  loop: "{{ lxc_host__containers | dict2items }}"
  loop_control:
    loop_var: item
  when: item.value.state == 'started' or item.value.state == 'stopped'
  vars:
    name: "{{ item.key }}"
    container: "{{ item.value }}"
    host: "{{ host_database[container.host_database if container.host_database is defined else name] }}"
    lan_if: "{{ container.interface if container.interface is defined else lxc_host__default_container_if_name }}"
    lan: "{{ host.interfaces[lan_if] }}"
    new: "{{ name in new_containers }}"
#  debug:
#    msg: "name={{name}}\nhost={{host}}\nlan={{lan}}\nnew={{new}}"
#  debug: msg=PRESENT
  include_tasks: per-host.yml

- name: Removing containers
  tags:
    - lxc-host
    - lxc-host-containers
  become: yes
  loop: "{{ lxc_host__containers | dict2items }}"
  loop_control:
    loop_var: item
  when: item.value.state == 'absent'
  lxc_container:
    name: "{{ item.key }}"
    state: absent