# 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: Find reachable hosts
  hosts: all
  gather_facts: false
  ignore_unreachable: true
  ignore_errors: true
  tasks:
    - name: Check for reachable nodes
      command: ping -c1 {{ inventory_hostname }}
      delegate_to: localhost
      register: ping_result
      ignore_errors: yes
      changed_when: false

    - name: Refresh ssh keys
      command: ssh-keygen -R {{ inventory_hostname }}
      delegate_to: localhost
      changed_when: false

    - name: Group reachable hosts
      group_by:
        key: "reachable"
      when: "'100% packet loss' not in ping_result.stdout"

- name: Get provision password
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Include vars file of inventory role
      include_vars: ../vars/main.yml

- name: Set hostname on reachable nodes and gather facts
  hosts: reachable
  gather_facts: False
  ignore_unreachable: true
  remote_user: "{{ cobbler_username }}"
  vars:
    ansible_password: "{{ cobbler_password }}"
    ansible_become_pass: "{{ cobbler_password }}"
    ansible_ssh_common_args: '-o StrictHostKeyChecking=no'
    mapping_file_present: ""
  tasks:
    - name: Setup
      setup:
       filter: ansible_*

    - name: Check hostname of server
      command: hostname
      register: hostname_check
      changed_when: false
      ignore_errors: true

    - name: Check if IP present in mapping file
      command: grep "{{ inventory_hostname }}" ../../provision/files/new_mapping_file.csv
      delegate_to: localhost
      register: file_present
      when: mapping_file == "true"
      ignore_errors: true

    - name: Set fact if mapping file present
      set_fact:
        mapping_file_present: file_present.stdout
      when: mapping_file == "true"
      ignore_errors: true

    - name: Get the static hostname from mapping file
      shell: awk -F',' '$3 == "{{ inventory_hostname }}" { print $2 }' ../../provision/files/new_mapping_file.csv
      delegate_to: localhost
      when: ('localhost' in hostname_check.stdout) and (mapping_file_present != "" ) and ( mapping_file == "true" )
      register: host_name
      ignore_errors: true

    - name: Set the hostname from mapping file
      hostname:
        name: "{{ host_name.stdout }}"
      register: result_host_name
      when: ('localhost' in hostname_check.stdout) and (mapping_file_present != "" ) and  (mapping_file == "true" )
      ignore_errors: true

    - name: Set the system hostname
      hostname:
        name: "compute{{ inventory_hostname.split('.')[-2] + '-' + inventory_hostname.split('.')[-1] }}"
      register: result_name
      when: ('localhost' in hostname_check.stdout) and (mapping_file_present == "")
      ignore_errors: true

    - name: Add new hostname to /etc/hosts
      lineinfile:
        dest: /etc/hosts
        regexp: '^127\.0\.0\.1[ \t]+localhost'
        line: "127.0.0.1 localhost {{ host_name.stdout }}"
        state: present
      when: ('localhost' in hostname_check.stdout) and ( mapping_file_present != "" ) and ( mapping_file == "true" )
      ignore_errors: true

    - name: Add new hostname to /etc/hosts
      lineinfile:
        dest: /etc/hosts
        regexp: '^127\.0\.0\.1[ \t]+localhost'
        line: "127.0.0.1 localhost 'compute{{ inventory_hostname.split('.')[-2] + '-' + inventory_hostname.split('.')[-1] }}'"
        state: present
      when: ('localhost' in hostname_check.stdout) and (mapping_file_present == "" )
      ignore_errors: true

- name: Update inventory
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Update inventory file
      block:
        - name: Fetch facts and add new hosts
          include_tasks: add_host.yml
          with_items: "{{ groups['reachable'] }}"
      when: "'reachable' in groups"

    - name: Show unreachable hosts
      debug:
        msg: "{{ host_unreachable_msg }} + {{ groups['ungrouped'] }}"
      when: "'ungrouped' in groups"