- name: add group
  group:
    name: "{{ item.group.name }}"
    gid: "{{ item.group.id | default(omit) }}"
  when: "item.group is defined"

- name: add/modify user
  user:
    name: "{{ item.username }}"
    uid: "{{ item.id | default(omit) }}"
    password: "{{ item.shadow_hash | default('*') }}"
    home: "{{ item.home_dir | default(omit) }}"
    groups: "{{ 'wheel' if item.shadow_hash is defined else omit }}"
    append: yes
    group: "{{ item.group.name if item.group is defined else omit }}"

- name: request password change on first login
  command: passwd -e {{ item.username }}
  when: item.require_password_change | d(false)

- name: add authorized key
  authorized_key:
    user: "{{ item.username }}"
    key: "{{ item['ssh-key'] }}"
  when: item['ssh-key'] is defined

- name: add private key
  copy:
    remote_src: yes
    src: "{{ config_mount_point + '/' + item['ssh-private-key'] }}"
    dest: "{{ '/root/.ssh/' if item.username=='root' else
           (item.home_dir | d('/home/' + item.username ) ) + '/.ssh' }}"
    mode: 0600
    owner: "{{ item.username }}"
    group: "{{ item.group.name if item.group is defined else item.username }}"
  when: item['ssh-private-key'] is defined
