# 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.
---

# This file used to generate a report of reachable and unreachable host of hpc cluster
# This file can be executed only if provisioned_hosts.yml is created inside the path omnia/appliance/roles/inventory/files/provisioned_hosts.yml

# Command to execute: ansible-playbook provision_report.yml -i ../roles/inventory/files/provisioned_hosts.yml

- 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: Group reachable hosts
      group_by:
        key: "reachable"
      when: "'100% packet loss' not in ping_result.stdout"

- name: Display hosts list
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Set reachable and unreachable host number
      set_fact:
        reachable_host_number: "{{ groups['reachable'] | length}}"
        unreachable_host_number: "{{ groups['ungrouped'] | length}}"

    - name: Copy dhcpd.leases from cobbler
      command: docker cp cobbler:/var/lib/dhcpd/dhcpd.leases dhcpd.leases
      changed_when: true

    - name: Fetch ethernet details of unreachable hosts
      shell: sed -n '/{{ item }}/,/ethernet/p' dhcpd.leases | grep "ethernet" | awk '{ print $3 }' | uniq
      register: ethernet_detail_unreachable
      changed_when: false
      args:
        warn: no
      with_items:
        - "{{ groups['ungrouped'] }}"

    - name: Fetch ethernet details of reachable hosts
      shell: sed -n '/{{ item }}/,/ethernet/p' dhcpd.leases | grep "ethernet" | awk '{ print $3 }' | uniq
      register: ethernet_detail_reachable
      changed_when: false
      args:
        warn: no
      with_items:
        - "{{ groups['reachable'] }}"

    - name: Copy host information to file
      template:
        src: provision_host_report.j2
        dest: provision_host_report.txt

    - name: Read provision host report
      command: cat provision_host_report.txt
      register: host_report
      changed_when: false

    - name: Display provision host report
      debug:
        var: host_report.stdout_lines