---
# file: roles/ssh-keygen-and-store/tasks/main.yml

- name: "getent passwd"
  getent:
    database: passwd
  tags: ssh-keygen

- name: "check if the ssh private key is already stored on hashicorp vault"
  command: "vault kv get -field=ssh_key_ed25519_{{ item }} talas-kv/{{ host_vars_location }}/{{ ansible_hostname }}"
  delegate_to: localhost
  become: False
  ignore_errors: True
  changed_when: False
  check_mode: no
  loop: "{{ ssh_keygen_user_list }}"
  register: hashicorp_private_keys
  tags: ssh-keygen

- name: "check if the ssh public key is already stored on hashicorp vault"
  command: "vault kv get -field=ssh_key_ed25519_{{ item }} talas-kv/{{ host_vars_location }}/{{ ansible_hostname }}"
  delegate_to: localhost
  become: False
  ignore_errors: True
  changed_when: False
  check_mode: no
  loop: "{{ ssh_keygen_user_list }}"
  register: hashicorp_public_keys
  tags: ssh-keygen

- name: "check if there is a private key on the remote server"
  shell: "cat $(getent passwd {{ item }} | cut -d':' -f6)/.ssh/id_ed25519"
  ignore_errors: True
  changed_when: False
  check_mode: no
  loop: "{{ ssh_keygen_user_list }}"
  register: local_private_keys
  tags: ssh-keygen

- name: "check if there is a public key on the remote server"
  shell: "cat $(getent passwd {{ item }} | cut -d':' -f6)/.ssh/id_ed25519.pub"
  ignore_errors: True
  changed_when: False
  check_mode: no
  loop: "{{ ssh_keygen_user_list }}"
  register: local_public_keys
  tags: ssh-keygen

- name: "key is nowhere"
  include_tasks: generate_key.yml
  with_nested:
    - "{{ hashicorp_private_keys.results }}"
    - "{{ local_private_keys.results }}"
  when:
    - item[0].item == item[1].item
    - item[0].failed
    - item[1].failed
  tags: ssh-keygen

- name: "key is only on the local server, sending it to hashicorp vault"
  include_tasks: from_server_to_hashicorp_vault.yml
  with_nested:
    - "{{ hashicorp_private_keys.results }}"
    - "{{ local_private_keys.results }}"
    - "{{ local_public_keys.results }}"
  when:
    - item[0].item == item[1].item
    - item[0].item == item[2].item
    - item[0].failed
    - not item[1].failed
  tags: ssh-keygen

- name: "key is only on hashicorp vault, it will be restored on the server"
  include_tasks: from_hashicorp_to_server.yml
  with_nested:
    - "{{ hashicorp_private_keys.results }}"
    - "{{ local_private_keys.results }}"
    - "{{ hashicorp_public_keys.results }}"
  when:
    - item[0].item == item[1].item
    - item[0].item == item[2].item
    - not item[0].failed
    - item[1].failed
  tags: ssh-keygen

- name: "checking that both private keys are the same"
  fail:
    msg: "The private key on hashicorp vault and the one on the server are different!"
  with_nested:
    - "{{ hashicorp_private_keys.results }}"
    - "{{ local_private_keys.results }}"
  when:
    - item[0].item == item[1].item
    - not item[0].failed
    - not item[1].failed
    - item[1].stdout != item[0].stdout
  tags: ssh-keygen
