---

- name: (interfaces.yml) Check if file /etc/network/interfaces.ORIG exists
  stat:
    path: /etc/network/interfaces.ORIG
  register: stat_result
  tags:
    - network-interfaces

- name: (interfaces.yml) Backup existing file '/etc/network/interfaces'
  command: cp -a /etc/network/interfaces /etc/network/interfaces.ORIG
  when: stat_result.stat.exists == False
  tags:
    - network-interfaces

- name: (interfaces.yml) Ensure interfaces file is latest
  template:
    src: "etc/network/interfaces.j2"
    dest: /etc/network/interfaces
  with_items: network_interfaces
  tags:
    - network-interfaces

- name: (interfaces.yml) Ensure imported device files at interfaces.d are latest
  template:
    src: "etc/network/interfaces.d/device.j2"
    dest: "{{ network_interface_path }}/device-{{ item.0 }}"
  with_items: 
    - "{{network_interfaces | default([]) | groupby('device') }}"
  register: network_configuration_result
  tags:
    - network-interfaces

# ---
# Remove device files not configured here
# ---

- name: (interfaces.yml) list existing files
  find:
    path: "{{ network_interface_path }}"
    file_type: file
  register: files_matched
  tags:
    - network-interfaces

- name: (interfaces.yml) configured files
  set_fact:
    network_configured_files: >
      [{% for item in network_configuration_result.results | default([]) -%}
        u"{{ item.dest | default(item.path) }}"
        {{ '' if loop.last else ',' }}
      {%- endfor %}]

- name: (interfaces.yml) remove configurations
  file:
    dest: "{{ item.path }}"
    state: absent
  when: item.path not in network_configured_files
  with_items: "{{ files_matched.files | default([]) }}"
