# 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.
# See the License for the specific language governing permissions and
# limitations under the License.
---
- name: Initializing variables
  set_fact:
    compute_list: []
    non_compute_list: []
    component_roles: []

- name: Get the hosts in node_inventory
  command: awx --conf.host {{ awx_host }} --conf.username {{ awx_admin_user }} --conf.password {{ awx_password }} --conf.insecure hosts list --inventory {{ node_inventory }} -f human --filter "name"
  changed_when: false
  no_log: true
  register: hosts_list

- name: Converting csv values to list
  read_csv:
    path: "{{ host_mapping_file_path }}"
    delimiter: ','
  register: mapping

- name: Collecting compute node ip's from host mapping file
  set_fact:
      compute_list: "{{ compute_list + [ item.IP ] }}"
  when:
    - item.Component_role ==  compute_node
    - item.IP in hosts_list.stdout
  no_log: true
  with_items:
      - "{{ mapping.list }}"

- name: Collecting manager,nfs_node,login_nodes ip's from host mapping file
  set_fact:
      non_compute_list: "{{ non_compute_list + [ item.IP ] }}"
      component_roles: "{{ component_roles + [item.Component_role] }}"
  when:
    - item.Component_role != compute_node
  no_log: true
  with_items:
      - "{{ mapping.list }}"

- name: Adding ips to compute node in awx ui
  block:
    - name: Add the host to compute group in node_inventory if it exists
      awx.awx.tower_group:
        name: "{{ compute_node }}"
        inventory: "{{ node_inventory }}"
        hosts: "{{ compute_list }}"
        tower_config_file: "{{ tower_config_file }}"
      register: compute_output
      no_log: true
  rescue:
    - name: Failed to add ip's to compute node in awx ui
      fail:
        msg: "{{ compute_output.stdout }}"

- name: Adding ips to manager,nfs_node,login_node in awx ui
  block:
    - name: Add the host to other groups in node_inventory if it exists
      awx.awx.tower_group:
        name: "{{ item.0 }}"
        inventory: "{{ node_inventory }}"
        hosts:
          - "{{ item.1 }}"
        tower_config_file: "{{ tower_config_file }}"
      when: item.1 in hosts_list.stdout
      with_together:
          - "{{ component_roles }}"
          - "{{ non_compute_list }}"
      register: non_compute_output
      no_log: true
  rescue:
    - name: Failed to add ip's to manager,nfs_node,login_node
      fail:
        msg: "{{ non_compute_output.stdout }}"