# Copyright 2022 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: Initialise host description
  set_fact:
    host_description: "Description Unavailable"
    
- name: Fetch description
  set_fact:
    host_description: "Service Tag: {{ service_tag }}"
  failed_when: false
  when: hostname_check.stdout is defined

- block:
    - name: Fetch the hosts in awx node inventory
      command: >-
        awx --conf.host {{ awx_host }} --conf.username {{ awx_username }} --conf.password {{ awx_password }}
        --conf.insecure hosts list --inventory node_inventory
      changed_when: false
      delegate_to: localhost
      no_log: true
      run_once: true
      register: fetch_hosts
  rescue:
    - name: Failed to fetch hosts in AWX
      fail:
        msg: "{{ fetch_hosts.stderr }}"
  
- block:
    - name: Add the host to awx node inventory if not present
      command: >-
        awx --conf.host {{ awx_host }} --conf.username {{ awx_username }} --conf.password {{ awx_password }}
        --conf.insecure hosts create --name {{ inventory_hostname }} --description "{{ host_description }}" --inventory node_inventory
      changed_when: true
      register: add_host_awx
      delegate_to: localhost
      no_log: true
      when:
        - hostname_check.stdout is defined
        - fetch_hosts.stdout is defined
        - inventory_hostname not in fetch_hosts.stdout
  rescue:
    - name: Failed to add host to AWX
      fail:
        msg: "{{ add_host_awx.stderr }}"
      when: add_host_awx is defined

- name: Host added msg
  debug:
    msg: "{{ hostvars['localhost']['host_added_msg'] + inventory_hostname }}"
  when:
    - host_description != "Description Unavailable"
    - add_host_awx is defined
    - add_host_awx is not failed