# Copyright 2021 Dell Inc. or its subsidiaries. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# limitations under the License.
---
- name: Check that device mapping file exists at mentioned path
  stat:
    path: "{{ mngmnt_mapping_file_path }}"
  register: stat_result
  tags: install

- name: Fail if config file doesn't exist
  fail:
    msg: "{{ fail_msg_mapping_file + mngmnt_mapping_file_path }}"
  when: not stat_result.stat.exists
  tags: install

- name: Read device mapping file from CSV file and return a dictionary
  read_csv:
    path: "{{ mngmnt_mapping_file_path }}"
    key: "{{ mapping_file_key }}"
  register: device_mapping_file
  delegate_to: localhost
  tags: install

- name: Check if header is present in mapping file
  shell:  set -o pipefail && awk 'NR==1 { print $1}' "{{ mngmnt_mapping_file_path }}"
  register: mngmnt_header
  changed_when: false
  tags: install

- name: Fail if header not in correct format
  fail:
    msg: "{{ fail_device_mapping_file_header }}"
  when: mngmnt_header.stdout !=  device_mapping_header_format
  tags: install

- name: Check if mapping file is comma seperated
  shell: awk -F\, '{print NF-1}' "{{ mngmnt_mapping_file_path }}"
  register: mngmnt_comma_seperated
  changed_when: false
  tags: install

- name: Fail if not comma seperated or if all fields are not given
  fail:
    msg: "{{ fail_mapping_file_field_seperation }}"
  when: not(item =="1")
  with_items: "{{ mngmnt_comma_seperated.stdout_lines }}"
  tags: install

- name: Initialize count variables
  set_fact:
    list_of_ips: []
    count_total_items: "{{ device_mapping_file.dict |length }}"
  tags: install

- name: Create list of IPs in mapping file
  set_fact:
    list_of_ips: "{{ [ item.value.IP ] + list_of_ips }}"
  loop: "{{ device_mapping_file.dict | dict2items }}"
  loop_control:
    label: "{{ item.value.MAC }}"
  tags: install

- name: Find count of unique IPs
  set_fact:
    count_of_unique_ip : "{{ list_of_ips| unique| length }}"
  tags: install

- name: Validation to check if unique IPs are provided for each node
  fail:
    msg: "{{ fail_mapping_file_duplicate_ip + mngmnt_mapping_file_path }}"
  when: not(count_of_unique_ip|int == count_total_items|int)
  tags: install
