---
# Create admin users BEFORE SSH hardening runs, so key-based access is in place
# before password authentication is turned off. Ordering matters here.

- name: Ensure the admin group exists
  ansible.builtin.group:
    name: "{{ linux_baseline_admin_group }}"
    state: present

- name: Grant the admin group passwordless-sudo (or full sudo) rights
  ansible.builtin.copy:
    dest: "/etc/sudoers.d/10-{{ linux_baseline_admin_group }}"
    content: >-
      %{{ linux_baseline_admin_group }} ALL=(ALL:ALL)
      {{ 'NOPASSWD:ALL' if linux_baseline_admin_nopasswd else 'ALL' }}
    owner: root
    group: root
    mode: "0440"
    validate: "visudo -cf %s"

- name: Create admin users
  ansible.builtin.user:
    name: "{{ item.name }}"
    groups: "{{ linux_baseline_admin_group }}"
    append: true
    shell: "{{ item.shell | default('/bin/bash') }}"
    state: present
  loop: "{{ linux_baseline_admin_users }}"
  loop_control:
    label: "{{ item.name }}"

- name: Install authorized SSH keys for admin users
  ansible.posix.authorized_key:
    user: "{{ item.name }}"
    key: "{{ item.authorized_keys | join('\n') }}"
    exclusive: "{{ linux_baseline_authorized_keys_exclusive | bool }}"
  loop: "{{ linux_baseline_admin_users }}"
  loop_control:
    label: "{{ item.name }}"
  when: item.authorized_keys | default([]) | length > 0
