- name: Create /home/zoox/imaging/ directory
  file:
    path: "{{ asset_root_directory }}/home/zoox/imaging/"
    owner: "{{ zoox_uid }}"
    group: "{{ zoox_gid }}"
    state: directory

- name: Install zoox-imaging key
  copy:
    content: "{{ lookup('hashi_vault_cache', 'secret=secret/ssh/zoox-imaging')[item.field] }}"
    dest: "{{ asset_root_directory }}/{{ item.file }}"
    mode: "{{ item.mode }}"
    owner: "{{ zoox_uid }}"
    group: "{{ zoox_gid }}"
  with_items:
    - { file: "{{ zoox_imaging_key_path }}.pub", field: 'client_rsa_public', mode: '644' }
    - { file: "{{ zoox_imaging_key_path }}", field: 'client_rsa_private', mode: '600' }

# TEMPORARY, until we set up CI etc. to use zaccess
- name: Add KI ssh key
  authorized_key:
    user: zoox
    key: "{{ lookup('hashi_vault_cache', 'secret=secret/ki_server/ssh').ssh_public_key }}"

- name: Install hosts file
  template:
    src: hosts
    dest:  "{{ asset_root_directory }}/etc/hosts"
    mode: '644'
    owner: root
    group: root
  become: yes

- set_fact:
    ssh_host_public_key_key_only: "{{ lookup('hashi_vault_cache', 'secret=secret/robot/ssh_host/' + zoox_robot_name)['ssh_public_key'].split()[1] }}"
  when: ssh_host_public_key_key_only is not defined

- name: Populate known hosts
  known_hosts:
    name: "{{ item.host }}"
    key: "{{ item.host }} {{ item.type }} {{ item.key }}"
    path: "{{ asset_root_directory }}/etc/ssh/ssh_known_hosts"
    state: present
  with_items:
    - { host: 'localhost', type: "ssh-rsa", key: "{{ ssh_host_public_key_key_only }}" }
    - { host: "{{ zoox_robot_name }}", type: "ssh-rsa", key: "{{ ssh_host_public_key_key_only }}" }
    - { host: 'git.zooxlabs.com', type: "ssh-rsa", key: "{{ git_zooxlabs_rsa }}" }
    - { host: 'git.zooxlabs.com', type: "ecdsa-sha2-nistp256", key: "{{ git_zooxlabs_ecdsa }}" }
    - { host: 'github.com', type: "ssh-rsa", key: "{{ github_rsa }}" }
  become: yes

- name: Add zoox-imaging to known hosts on imaging machine
  lineinfile:
    path: "{{ asset_root_directory }}/{{ imaging_known_hosts }}"
    line: "zoox-imaging,{{ imaging_interface_subnet }}.* {{ lookup('hashi_vault_cache', 'secret=secret/ssh/zoox-imaging').host_rsa_public }}"
    create: yes
    owner: "{{ zoox_uid }}"
    group: "{{ zoox_gid }}"

- name: Copy ansible configuration variables
  template:
    src: ansible_configuration.json
    dest: "{{ asset_root_directory }}/{{ imaging_root }}ansible_configuration.json"
    owner: "{{ zoox_uid }}"
    group: "{{ zoox_gid }}"
    mode: '755'
