---
# create separate users for perfact employees
# add them to group perfact_service
# and deploys their ssh-keys

- name: compile per-host user list
  set_fact:
    relevant_users: "{{ users | users_having_access(hostvars[inventory_hostname]) }}"
  changed_when: False

#- debug:
#    msg:
#      relevant_users: "{{ relevant_users }}"

#- debug:
#    msg:
#      relevant_users as list: "{{ relevant_users.keys() | list }}"

# make it nicer - create a new dict with only user and ssh-key
- name: create dict with user and ssh-keys
  set_fact:
    perfact_service_users: "{{ relevant_users | map_dict_values_to_subkey('ssh_keys') |  map_dict_values_to_subkey('pffile') }}"
    # will create:
    #"ansible_facts": {
    #  "users_mail_virtual": {
    #      "mmustermann": [
    #          "mmustermann@perfact.de",
    #          "mmu@perfact.de"
    #      ],
  changed_when: False

- debug:
    msg:
      perfact_service_users: "{{ perfact_service_users }}"
    #msg: perfact_service_users als list: "{{ perfact_service_users | list }}"

#- meta:
#    end_play

- assert:
    that:
    - perfact_service_users | length > 0

- name: create group perfact_service
  become: true
  group:
    name: perfact_service

- name: create users in groups perfact_service
  become: true
  user:
    name: "{{ item }}"
    groups: perfact_service
    shell: /bin/bash
  with_items: "{{ perfact_service_users.keys() | list }}"

#- debug:
#    msg:
#      searching ssh_keys: "{{ relevant_users | dict2items }}"

- name: create authorized_key for perfact employees
  become: true
  authorized_key:
    user: "{{ item.key }}"
    key: "{{ item.value }}"
    exclusive: true
  with_items: "{{ perfact_service_users | dict2items }}"

- name: store users in group perfact_service
  shell: "grep '^perfact_service:.*$' /etc/group | cut -d: -f4"
  register:
    perfact_users_on_system
  changed_when: False

- name: print users in group perfact_service
  debug:
    var: perfact_users_on_system.stdout

#  FIXME  - this is not working
#  - name: delete users that are no longer there
#    become: true
#    user:
#      name: "{{ item }}"
#      remove: true
#    with_items: "{{ perfact_users_on_system.stdout_lines[0].split(',') | difference(perfact_users.keys()) }}"
