# Copyright 2020 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: Check if host already exists
  command: awk "{{ '/'+ item + '/' }}" /root/inventory
  register: check_host
  changed_when: no

- name: Initialise host description
  set_fact:
    host_description: "Description Unavailable"

- name: Fetch description
  set_fact:
    host_description: "CPU:{{ hostvars[item]['ansible_processor_count'] }}
    Cores:{{ hostvars[item]['ansible_processor_cores'] }}
    Memory:{{ hostvars[item]['ansible_memtotal_mb'] }}MB
    BIOS:{{ hostvars[item]['ansible_bios_version'] }}"
  when: not check_host.stdout | regex_search(item)
  ignore_errors: yes

- name: Add host
  lineinfile:
    path:  "/root/inventory"
    line: "    {{ item }}:\n      _awx_description: {{ host_description }}"
  when:
    - not check_host.stdout | regex_search(item)
    - host_description != "Description Unavailable"

- name: Host added msg
  debug:
    msg: "{{ host_added_msg + item }}"
  when:
    - not check_host.stdout | regex_search(item)
    - host_description != "Description Unavailable"
