---
# SPDX-license-identifier: Apache-2.0
##############################################################################
# Copyright (c) 2017 Ericsson AB and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
##############################################################################
- name: ensure glean rules are removed
  file:
    path: "/etc/udev/rules.d/99-glean.rules"
    state: absent

- name: Determine required packages
  set_fact:
    network_packages:
      - bridge-utils
      - "{{ (ansible_pkg_mgr in ['zypper', 'apt']) | ternary('iproute2', 'iproute') }}"
      - "{{ (ansible_pkg_mgr == 'apt') | ternary('vlan', 'bridge-utils') }}"
      - iptables

- name: Ensure networking packages are present
  package:
    name: "{{ network_packages }}"
    state: present

- name: Ensure local facts directory exists
  file:
    path: "/etc/ansible/facts.d"
    state: directory

# NOTE(hwoarang) We have to check all levels of the local fact before we add it
# otherwise Ansible will fail.
- name: Record initial active interface
  ini_file:
    create: yes
    section: network
    state: present
    option: xci_interface
    value:  "{{ ansible_default_ipv4.interface }}"
    path: "/etc/ansible/facts.d/xci.fact"
  when: ansible_local is not defined
    or (ansible_local is defined and ansible_local.xci is not defined)
    or (ansible_local is defined and ansible_local.xci is defined and ansible_local.xci.network is not defined)
    or (ansible_local is defined and ansible_local.xci is defined and ansible_local.xci.network is defined and ansible_local.xci.network.xci_interface is not defined)
  notify:
    - Reload facts

- name: Run handlers
  meta: flush_handlers

- name: "Configure networking on {{ ansible_os_family }}"
  include_tasks: "network_{{ ansible_os_family | lower }}.yml"

- name: Wait for host to come back to life
  local_action:
    module: wait_for
    host: "{{ ansible_host }}"
    delay: 15
    state: started
    port: 22
    connect_timeout: 10
    timeout: 180