---

- name: Install required packages
  apt:
    state: present
    name:
      - psmisc
      - sudo

- name: Create new user {{ bootstrap_expected_user }}
  user:
    state: present
    name: "{{ bootstrap_expected_user }}"
    groups:
      - sudo
    append: yes
    password: "{{ bootstrap_expected_become_pass | password_hash('sha512', LOCAL_SALT) }}"
    update_password: on_create
  register: bootstrap_expected_user_data

- name: Copy SSH Keys if bootstraped now
  when: bootstrap_used
  block:
    - name: Retrieve data from user {{ bootstrap_user }}
      user:
        name: "{{ bootstrap_user }}"
        state: present
      register: bootstrap_user_data
    - name: Be sure old user has .ssh directory
      file:
        state: directory
        path: "{{ bootstrap_user_data.home }}/.ssh"
        owner: "{{ bootstrap_user }}"
        group: "{{ bootstrap_user }}"
        mode: "u=rwx,g=rx,o="
    - name: Be sure old user has authorized_keys file
      file:
        state: touch
        path: "{{ bootstrap_user_data.home }}/.ssh/authorized_keys"
        owner: "{{ bootstrap_user }}"
        group: "{{ bootstrap_user }}"
        mode: "u=rw,g=r,o="
    - name: Create .ssh directory for user {{ bootstrap_expected_user }}
      file:
        path: "{{ bootstrap_expected_user_data.home }}/.ssh"
        state: directory
        owner: "{{ bootstrap_expected_user }}"
        group: "{{ bootstrap_expected_user }}"
      become: yes
    - name: Transfer SSH keys to new user
      copy:
        remote_src: yes
        src: "{{ bootstrap_user_data.home }}/.ssh/authorized_keys"
        dest: "{{ bootstrap_expected_user_data.home }}/.ssh/authorized_keys"
        owner: "{{ bootstrap_expected_user }}"
        group: "{{ bootstrap_expected_user }}"
        mode: u=rw,g=r,o=
      become: yes

- name: Configure given SSH key for new user
  authorized_key:
    state: present
    user: "{{ bootstrap_expected_user }}"
    key: "{{ lookup('file', '/home/zocker/.ssh/id_ed25519.pub') }}"
  when: inventory_hostname != "localhost"
