---
# Формирование плоского списка пользователей, которые должны существовать на ЭТОМ хосте,
# путём выборки только тех групп администраторов, что указаны в `users_allowed_admin_groups`.
- name: Build list of users to manage on this host
  ansible.builtin.set_fact:
    users_managed_users: >-
      {{
        users_allowed_admin_groups
        | map('extract', users_admin_groups)
        | flatten
        | unique
      }}

- name: Show managed users for this host
  ansible.builtin.debug:
    msg: "Managing users: {{ users_managed_users | map(attribute='username') | list }}"

# ── Необходимые пакеты ────────────────────────────────────────────────────────
- name: Update apt cache (Debian/Ubuntu)
  ansible.builtin.apt:
    update_cache: true
    cache_valid_time: 3600
  when: ansible_os_family == "Debian"
  failed_when: false

- name: Ensure sudo package is present (Debian/Ubuntu)
  ansible.builtin.apt:
    name: sudo
    state: present
  when: ansible_os_family == "Debian"

# ── Учётные записи пользователей ──────────────────────────────────────────────
- name: Ensure user accounts exist
  ansible.builtin.user:
    name: "{{ item.username }}"
    state: present
    shell: /bin/bash
    create_home: true
  loop: "{{ users_managed_users }}"
  loop_control:
    label: "{{ item.username }}"

# ── Членство в группах ────────────────────────────────────────────────────────
- name: Add users to privileged group ({{ users_sudo_group }})
  ansible.builtin.user:
    name: "{{ item.username }}"
    groups: "{{ users_sudo_group }}"
    append: true
  loop: "{{ users_managed_users }}"
  loop_control:
    label: "{{ item.username }}"

# ── Sudo без пароля ───────────────────────────────────────────────────────────
- name: Remove legacy sudoers files with dots in name
  ansible.builtin.file:
    path: /etc/sudoers.d/{{ item.username }}
    state: absent
  loop: "{{ users_managed_users }}"
  loop_control:
    label: "{{ item.username }}"
  when: "'.' in item.username"

- name: Configure passwordless sudo via sudoers.d
  ansible.builtin.copy:
    content: "{{ item.username }} ALL=(ALL) NOPASSWD:ALL\n"
    dest: /etc/sudoers.d/{{ item.username | replace('.', '_') }}
    owner: root
    group: root
    mode: "0440"
    validate: visudo -cf %s
  loop: "{{ users_managed_users }}"
  loop_control:
    label: "{{ item.username }}"

# ── SSH-ключи ─────────────────────────────────────────────────────────────────
- name: Deploy SSH authorized keys
  ansible.posix.authorized_key:
    user: "{{ item.username }}"
    key: "{{ item.ssh_key }}"
    state: present
    exclusive: false
  loop: "{{ users_managed_users }}"
  loop_control:
    label: "{{ item.username }}"
  when:
    - item.ssh_key is defined
    - item.ssh_key | length > 0
