---
# Many parts stolen from https://serverfault.com/a/913211

- name: Get list of users from GitLab group
  run_once: true
  local_action:
    module: ansible.builtin.uri
    url: "https://{{ gitlab_host }}/api/v4/groups/{{ group_id }}/members"
    method: GET
    headers:
      Authorization: "Bearer {{ gitlab_token }}"
  register: "gitlab_group_members"

- name: Retrieve user keys
  loop: "{{ gitlab_group_members.json }}"
  loop_control:
    label: "{{ item.username }}"
  run_once: true
  local_action:
    module: ansible.builtin.uri
    url: "https://{{ gitlab_host }}/{{ item.username }}.keys"
    method: GET
    headers:
      Authorization: "Bearer {{ gitlab_token }}"
    return_content: true
  register: "user_ssh_keys"


- name: Create "ansiblemanaged" group
  ansible.builtin.group:
    name: ansiblemanaged
    state: present

- name: Create users in the managed group
  ansible.builtin.user:
    name: "{{ item.username }}"
    groups: ["ansiblemanaged"]
    shell: /bin/bash
    state: present
  with_items: "{{ gitlab_group_members.json }}"

- name: Determine existing, ansiblemanaged users
  ansible.builtin.shell: 'grep ansiblemanaged /etc/group | cut -d: -f4 | tr "," "\n"'
  changed_when: false 
  register: existing_users

- name: Determine users on linux, but not in GitLab group
  ansible.builtin.set_fact:
    users_to_remove: "{{ existing_users.stdout_lines | difference(gitlab_group_members.json | map(attribute='username')) }}"

- name: Remove users, who are not in the GitLab group
  ansible.builtin.user:
    name: "{{ item }}"
    state: absent
  with_items: "{{ users_to_remove }}"

- name: Add public ssh keys of users
  ansible.posix.authorized_key:
    user: "{{ item.0 }}"
    exclusive: false
    key: "{{ item.1 }}"
    state: present
  with_together:
    - "{{ gitlab_group_members.json | map(attribute='username') }}"
    - "{{ user_ssh_keys.results | map(attribute='content') }}"
