---

- name: Contiv | Wait for netmaster
  uri:
    url: "http://127.0.0.1:{{ contiv_netmaster_port }}/info"
  register: result
  until: result.status is defined and result.status == 200
  retries: 10
  delay: 5

- name: Contiv | Get global configuration
  command: |
    {{ bin_dir }}/netctl --netmaster "http://127.0.0.1:{{ contiv_netmaster_port }}" \
    global info --json --all
  register: global_config
  run_once: true
  changed_when: false

- set_fact:
    contiv_global_config: "{{ (global_config.stdout|from_json)[0] }}"

- name: Contiv | Set global forwarding mode
  command: |
    {{ bin_dir }}/netctl --netmaster "http://127.0.0.1:{{ contiv_netmaster_port }}" \
      global set --fwd-mode={{ contiv_fwd_mode }}
  when: "contiv_global_config.get('fwdMode', '') != contiv_fwd_mode"
  run_once: true

- name: Contiv | Set global fabric mode
  command: |
    {{ bin_dir }}/netctl --netmaster "http://127.0.0.1:{{ contiv_netmaster_port }}" \
      global set --fabric-mode={{ contiv_fabric_mode }}
  when: "contiv_global_config.networkInfraType != contiv_fabric_mode"
  run_once: true

- name: Contiv | Get existing networks
  command: |
    {{ bin_dir }}/netctl --netmaster "http://127.0.0.1:{{ contiv_netmaster_port }}" \
    net ls -q
  register: net_result
  run_once: true
  changed_when: false

- name: Contiv | Create networks
  command: |
    {{ bin_dir }}/netctl --netmaster "http://127.0.0.1:{{ contiv_netmaster_port }}" \
      net create \
      --encap={{ item.encap|default("vxlan") }} \
      --gateway={{ item.gateway }} \
      --nw-type={{ item.nw_type|default("data") }} \
      --pkt-tag={{ item.pkt_tag|default("0") }} \
      --subnet={{ item.subnet }} \
      --tenant={{ item.tenant|default("default") }} \
      "{{ item.name }}"
  with_items: "{{ contiv_networks }}"
  when: item['name'] not in net_result.stdout_lines
  run_once: true

- name: Contiv | Check if default group exists
  command: |
    {{ bin_dir }}/netctl --netmaster "http://127.0.0.1:{{ contiv_netmaster_port }}" \
    group ls -q
  register: group_result
  run_once: true
  changed_when: false

- name: Contiv | Create default group
  command: |
    {{ bin_dir }}/netctl --netmaster "http://127.0.0.1:{{ contiv_netmaster_port }}" \
    group create default-net default
  when: "'default' not in group_result.stdout_lines"
  run_once: true
