---
- name: Gather os specific variables
  include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_facts.distribution }}-{{ ansible_facts.distribution_major_version }}.yml"
        - "{{ ansible_facts.distribution }}.yml"
        - "{{ ansible_facts.os_family }}.yml"
      skip: true
  tags: vars

- name: Ensure general system requirements are installed
  package:
    name: "{{ system_requirements }}"
  register: result
  until: result is success
  retries: 3
  become: true
  # Don't uninstall requirements during teardown since they may already have
  # been present.
  when: cmd != 'teardown'

- name: Ensure log directory exists
  file:
    path: "{{ log_directory }}"
    state: directory
    mode: "0755"
  become: true
  # Don't remove log directory during teardown to preserve historical logs.
  when: cmd != 'teardown'

- name: Check if OVS is installed
  when: bridge_type == "openvswitch"
  block:
    - name: Check if ovs-vsctl command is present
      command: ovs-vsctl --version
      register: ovs_vsctl_check
      failed_when: false
      changed_when: false

    - name: Fail when Open vSwitch is not installed
      fail:
        msg: >-
          Tenks requires openvswitch to be installed and running. Please install
          openvswitch. If it is installed, please report this as a bug.
      # Assume a non-zero return code means that openvswitch is not installed.
      when: ovs_vsctl_check.rc != 0

- name: Configure physical networks
  include_tasks: physical_network.yml
  vars:
    network_name: "{{ pn.key }}"
    tenks_bridge: "{{ bridge_prefix ~ (pn.key | physnet_name_to_index) }}"
    source_interface: "{{ pn.value }}"
    state: "{{ 'absent' if cmd == 'teardown' else 'present' }}"
  loop: "{{ query('dict', physnet_mappings) }}"
  loop_control:
    loop_var: pn