# 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: Set Facts
  set_fact:
    ansible_ssh_common_args: '-o StrictHostKeyChecking=no'

- name: Fetch the execution environment
  command: hostname
  register: host_name
  changed_when: false

- name: Install sshpass
  package:
    name: sshpass
    state: present
  when: awx_search_key not in host_name.stdout

- name: Check if provisioned host file exists
  stat:
    path: "{{ provisioned_hosts_file }}"
  register: provisioned_file

- name: Include variable file base_vars.yml
  include_vars: "{{ base_vars_file }}"
  
- name: Update inventory
  block:
    - name: Check if {{ login_vars_file }} file is encrypted
      command: cat {{ login_vars_file }}
      changed_when: false
      no_log: true
      register: config_content
      run_once: true

    - name: Decrpyt {{ login_vars_file }}
      command: >-
        ansible-vault decrypt {{ login_vars_file }}
        --vault-password-file {{ login_vault_file }}
      when: "'$ANSIBLE_VAULT;' in config_content.stdout"
      changed_when: false
      run_once: true

    - name: Include variable file {{ login_vars_file }}
      include_vars: "{{ login_vars_file }}"
      no_log: true
      run_once: true
    
    - name: Save input variables from file
      set_fact:
        mapping_file: false

    - name: Check the status for mapping file
      set_fact:
        mapping_file: true
      when: host_mapping_file_path

    - name: Encrypt {{ login_vars_file }}
      command: >-
        ansible-vault encrypt {{ login_vars_file }}
        --vault-password-file {{ login_vault_file }}
      changed_when: false
      when: "'$ANSIBLE_VAULT;' in config_content.stdout"
      run_once: true

    - name: Add inventory playbook
      block:
        - name: add hosts with description to inventory file
          command: >-
            ansible-playbook -i {{ provisioned_hosts_file }}
            {{ role_path }}/files/create_inventory.yml
            --extra-vars "host_username={{ host_username }} host_password={{ provision_password }} mapping_file={{ mapping_file | bool }}"
          no_log: True
          register: register_error
      rescue:
        - name: Fail if host addition was not successful
          fail:
            msg: "{{ register_error.stderr + register_error.stdout | regex_replace(host_username) | regex_replace(provision_password) }}"
  when: provisioned_file.stat.exists