---
- name: Check that virthost/undercloud is set
  fail:
    msg: "You need to set virthost/undercloud before running these playbooks."
  when: virthost is not defined

- name: Ensure local working dir exists
  file:
    path: "{{ local_working_dir }}"
    state: directory

- name: Create empty ssh config file
  file:
    path: "{{ local_working_dir }}/ssh.config.ansible"
    state: touch

- name: Create initial ssh config file with virthost_key (if defined)
  blockinfile:
    dest: "{{ local_working_dir }}/ssh.config.ansible"
    block: |
      Host {{ virthost }}
          Hostname {{ virthost }}
          IdentityFile {{ virthost_key }}
          User root
          StrictHostKeyChecking no
          UserKnownHostsFile=/dev/null
  when: virthost_key is defined

- name: Add the virthost to the inventory
  add_host:
    name: "{{ virthost }}"
    groups: "virthost"
    ansible_fqdn: "{{ virthost }}"
    ansible_user: "root"
    ansible_host: "{{ virthost }}"

- name: Create virthost/undercloud access key
  command: >
    ssh-keygen -f {{ undercloud_key }} -N ''
    -C 'ansible_generated_virt_host'
    -t rsa -b 4096
  args:
    creates: "{{ undercloud_key }}"

- name: Create non-root user on virthost/undercloud
  delegate_to: "{{ virthost }}"
  user:
    name: "{{ non_root_user }}"
    state: present
    shell: /bin/bash
  become: true

- name: Configure non-root user authorized_keys on virthost/undercloud
  delegate_to: "{{ virthost }}"
  authorized_key:
    user: "{{ non_root_user }}"
    key: "{{ lookup('file', undercloud_key|quote + '.pub')|default('') }}"
  become: true

- name: Grant sudo privileges to non-root user on virthost/undercloud
  delegate_to: "{{ virthost }}"
  copy:
    content: |
      {{ non_root_user }} ALL=(ALL) NOPASSWD:ALL
    dest: /etc/sudoers.d/{{ non_root_user }}
    owner: root
    group: root
    mode: 0440
  become: true

- name: get undercloud ip
  delegate_to: "{{ virthost }}"
  shell: ip route get 1 | awk '{print $NF;exit}'
  register: registered_undercloud_ip

- name: Re-add the virthost to the inventory
  add_host:
    name: "{{ virthost }}"
    groups: "virthost"
    ansible_fqdn: "{{ virthost }}"
    ansible_user: "{{ non_root_user }}"
    ansible_host: "{{ virthost }}"
    ansible_private_key_file: "{{ undercloud_key }}"

# Add the undercloud to the in-memory inventory.
- name: Add undercloud machine to inventory
  add_host:
    name: undercloud
    groups: undercloud
    ansible_host: undercloud
    ansible_fqdn: undercloud
    ansible_user: "{{ undercloud_user }}"
    ansible_private_key_file: "{{ undercloud_key }}"
    ansible_ssh_extra_args: '-F "{{local_working_dir}}/ssh.config.ansible"'
    ansible_scp_extra_args: '-F "{{local_working_dir}}/ssh.config.ansible"'
    ansible_sftp_extra_args: '-F "{{local_working_dir}}/ssh.config.ansible"'
    undercloud_ip: "{{ registered_undercloud_ip.stdout }}"
