---
- name: Create sshusers group
  ansible.builtin.group:
    name: sshusers
    state: present
    system: true

- name: Create ansible automation user
  ansible.builtin.user:
    name: ansible
    comment: "Ansible Automation User"
    state: present
    shell: /bin/bash
    groups: [sudo, sshusers]
    append: true

- name: Create .ssh directory for ansible user
  ansible.builtin.file:
    path: /home/ansible/.ssh
    state: directory
    owner: ansible
    group: ansible
    mode: "0700"

- name: Install ansible user SSH public key
  ansible.posix.authorized_key:
    user: ansible
    key: "{{ lookup('file', ansible_user_ssh_public_key_file) }}"
    exclusive: true
    state: present
  when: ansible_user_ssh_public_key_file is defined

- name: Configure passwordless sudo for ansible user
  ansible.builtin.lineinfile:
    path: /etc/sudoers.d/099_ansible_automation
    line: "ansible ALL=(ALL) NOPASSWD: ALL"
    create: true
    mode: "0440"
    validate: "/usr/sbin/visudo -cf %s"

- name: Add sudo command logging for ansible user
  ansible.builtin.lineinfile:
    path: /etc/sudoers.d/099_ansible_automation
    line: "Defaults:ansible log_output"
    insertafter: "^ansible ALL="
    validate: "/usr/sbin/visudo -cf %s"

- name: Configure your personal admin user (with password sudo)
  ansible.builtin.user:
    name: "{{ ansible_user_admin_name }}"
    comment: "System Administrator"
    state: present
    shell: /bin/bash
    groups: [sudo, sshusers]
    append: true
  when: ansible_user_admin_name is defined

- name: Install your personal SSH public key
  ansible.posix.authorized_key:
    user: "{{ ansible_user_admin_name }}"
    key: "{{ lookup('file', ansible_user_admin_ssh_public_key_file) }}"
    exclusive: false
    state: present
  when:
    - ansible_user_admin_name is defined
    - ansible_user_admin_ssh_public_key_file is defined

- name: Configure password-required sudo for personal admin
  ansible.builtin.lineinfile:
    path: /etc/sudoers.d/010_admin_user
    line: "{{ ansible_user_admin_name }} ALL=(ALL:ALL) ALL"
    create: true
    mode: "0440"
    validate: "/usr/sbin/visudo -cf %s"
  when: ansible_user_admin_name is defined
