# For live customization, these variables are set by live_robot_inventory.py
- set_fact:
    ssh_public_key: "{{ lookup('hashi_vault_cache', 'secret=secret/robot/ssh/' + zoox_robot_name)['ssh_public_key'] }}"
  when: ssh_public_key is not defined
- set_fact:
    ssh_private_key: "{{ lookup('hashi_vault_cache', 'secret=secret/robot/ssh/' + zoox_robot_name)['ssh_private_key'] }}"
  when: ssh_private_key is not defined
- set_fact:
    ssh_host_public_key: "{{ lookup('hashi_vault_cache', 'secret=secret/robot/ssh_host/' + zoox_robot_name)['ssh_public_key'] }}"
  when: ssh_host_public_key is not defined
- set_fact:
    ssh_host_private_key: "{{ lookup('hashi_vault_cache', 'secret=secret/robot/ssh_host/' + zoox_robot_name)['ssh_private_key'] }}"
  when: ssh_host_private_key is not defined

- name: Install ssh client keys
  copy:
    content: "{{ item.key }}"
    dest: "{{ asset_root_directory }}/home/zoox/.ssh/{{ item.dest }}"
    mode: "{{ item.mode }}"
    owner: "{{ zoox_uid }}"
    group: "{{ zoox_gid }}"
  no_log: yes
  with_items:
    - { key: "{{ ssh_public_key }}", dest: id_rsa.pub, mode: "0644" }
    - { key: "{{ ssh_private_key }}", dest: id_rsa, mode: "0600" }

- name: Install ssh host keys
  copy:
    content: "{{ item.key }}"
    dest: "{{ asset_root_directory }}/etc/ssh/{{ item.dest }}"
    mode: "{{ item.mode }}"
    owner: root
    group: root
  no_log: yes
  become: yes
  with_items:
    - { key: "{{ ssh_host_public_key }}", dest: ssh_host_rsa_key.pub, mode: "0644" }
    - { key: "{{ ssh_host_private_key }}", dest: ssh_host_rsa_key, mode: "0600" }

# Not a handler because other machines' host keys might change even if this machine's do not.
# Don't clear /etc/ssh/ssh_known_hosts since the 'ssh_known_hosts' role should manage that file.
- name: Clear zoox user ssh known hosts
  # Use 'copy' module for easy backup
  copy:
    content: ""
    dest: "{{ asset_root_directory }}/home/zoox/.ssh/known_hosts"
    backup: yes
    owner: "{{ zoox_uid }}"
    group: "{{ zoox_gid }}"
    mode: '600'
  become: yes
  when: is_live_update
