- name: Setup ssh dir
  file:
    path: "{{ home }}/.ssh"
    state: directory
    recurse: true
    owner: "{{ user }}"

- name: Copy pre-generated ssh keys
  when: "not target_is_real"
  block:
    - copy:
        src: ./vm_files/remote_key
        dest: "{{ home }}/.ssh/{{ device_name }}_generic_ed25519"
        mode: u=rw,g=,o=
    - copy:
        src: ./vm_files/remote_key.pub
        dest: "{{ home }}/.ssh/{{ device_name }}_generic_ed25519.pub"
        mode: u=rw,g=,o=

- name: Config git
  template:
    src: ssh_config
    dest: "{{ home }}/.ssh/config"
    owner: "{{ user }}"
    mode: u=rw,g=,o=

- name: Create temporary build directory
  ansible.builtin.tempfile:
    state: directory
    suffix: ssh_known_hosts
  register: tempdir_known_hosts

- name: Load known hosts from profiles
  template:
    # load from controller host
    src: "{{ home }}/.dots/profiles/{{ item.name }}/configs/ssh/known_hosts"
    dest: "{{ tempdir_known_hosts.path }}/{{ item.name }}"
  with_items: "{{ enabled_profiles }}"

- name: Concat known hosts
  template:
    src: ssh/known_hosts
    dest: "{{ home }}/.ssh/known_hosts"
  vars:
    tempdir_known_hosts: "{{ tempdir_known_hosts }}"

- name: Ensure ssh config profiles dir exists
  file:
    path: "{{ home }}/.ssh/profiles"
    state: directory

- name: Load ssh config of profiles
  template:
    src: "{{ home }}/.dots/profiles/{{ item.name }}/configs/ssh/config"
    dest: "{{ home }}/.ssh/profiles/{{ item.name }}"
    mode: u=rw,g=,o=
  with_items: "{{ enabled_profiles }}"