- name: set hostname
  hostname:
    name: "{{ network.hostname | default(inventory_hostname) }}"

- name: touch user and group cache files
  file:
    path: "{{ '/etc/%s' | format(item) }}"
    state: touch
    mode: 0644
  with_items:
    - "managed_users"
    - "managed_groups"

- name: remove obsolete groups from the system
  group:
    name: "{{ item }}"
    state: absent
  when: not item in usergroups
  with_lines: cat /etc/managed_groups

- name: remove obsolete groups from managefile 
  lineinfile:
    path: /etc/managed_groups
    regexp: "^{{ item }}"
    state: absent
  when: not item in usergroups
  with_lines: cat /etc/managed_groups

- name: remove obsolete users from the system
  group:
    name: "{{ item }}"
    remove: yes
    state: absent
  when: not item in users
  with_lines: cat /etc/managed_users

- name: remove obsolete users from managefile 
  lineinfile:
    path: /etc/managed_users
    regexp: "^{{ item }}"
    state: absent
  when: not item in users
  with_lines: cat /etc/managed_users

- name: add groups
  group:
    name: "{{ item.key }}"
    system: "{{ item.value.system | default(False) }}"
  with_dict: "{{ usergroups | default({}) }}"

- name: add users
  user:
    name: "{{ item.key }}"
    group: "{{ item.value.group | default(item.key) }}"
    system: "{{ item.value.system | default(False) }}"
    home: "{{ item.value.home | default('/home/%s' | format(item.key)) }}"
    shell: "{{ item.value.shell | default('/bin/sh') }}"
    password: "{{ item.value.password | default('') }}"
    createhome: "{{ item.value.createhome | default(True) }}"
    expires: "{{ item.value.expires | default(None) }}"
  with_dict: "{{ users | default({}) }}"
    
- name: update user groups
  user:
    name: "{{ item.name }}"
    append: True
    groups: "{{ item.groups }}"
  when: (item.groups | length()) > 0
  with_items: "{{ system_users | default([]) }}"

- name: update groups in managefile 
  lineinfile:
    path: /etc/managed_groups
    line: "{{ item.key }}"
  with_dict: "{{ usergroups | default({}) }}"

- name: update users in managefile 
  lineinfile:
    path: /etc/managed_users
    line: "{{ item.key }}"
  with_dict: "{{ users | default({}) }}"

- name: set timezone
  timezone:
    name: "{{ timezone | default('Europe/Berlin') }}"