#  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: Initialize variables
  set_fact:
    ssh_status: false
    current_host: "{{ item }}"

- name: Refresh ssh-key if changed
  command: ssh-keygen -R {{ current_host }}
  changed_when: False
  failed_when: false
  when: "'manager' in group_names"

- name: Verify whether passwordless ssh is set on the remote host
  shell: sshpass ssh -o "PasswordAuthentication=no" root@{{ current_host }} 'hostname'
  register: ssh_output
  async: 30
  poll: 5
  failed_when: false
  changed_when: false

- name: Update ssh connection status
  set_fact:
    ssh_status: true
  when:
    - "'Permission denied' not in ssh_output.stderr"
    -  ssh_output.stdout | length > 2

- name: Verify the public key file existence
  stat:
    path: "{{ rsa_id_file }}"
  register: verify_rsa_id_file
  when: not ssh_status

- name: Generate ssh key pair
  command: ssh-keygen -t rsa -b 4096 -f "{{ rsa_id_file }}" -q -N "{{ passphrase }}"
  when:
    - not ssh_status
    - not verify_rsa_id_file.stat.exists

- name: Add the key identity
  shell: |
    eval `ssh-agent -s`
    ssh-add "{{ rsa_id_file }}"
  when: not ssh_status

- name: Post public key
  block:
    - name: Create .ssh directory
      command: >-
        sshpass -p "{{ hostvars['127.0.0.1']['cobbler_password'] }}"
        ssh root@"{{ current_host }}" mkdir -p /root/.ssh
      when: not ssh_status
      no_log: True
      register: register_error

    - name: Copy the public key to remote host
      shell: >-
        set -o pipefail && cat "{{ rsa_id_file }}".pub
        | sshpass -p "{{ hostvars['127.0.0.1']['cobbler_password'] }}"
        ssh root@"{{ current_host }}" 'cat >> "{{ auth_key_path }}"'
      when: not ssh_status
      no_log: True
      register: register_error

    - name: Change permissions on the remote host
      shell: sshpass -p "{{ hostvars['127.0.0.1']['cobbler_password'] }}" ssh root@"{{ current_host }}" 'chmod 700 .ssh; chmod 640 "{{ auth_key_path }}"'
      when: not ssh_status
      no_log: True
      register: register_error

  rescue:
    - name: Passwordless ssh failed
      fail:
        msg: "{{ register_error.stderr | regex_replace(hostvars['127.0.0.1']['cobbler_password']) | regex_replace(auth_key_path) }}"