---
- name: user | Install doas
  apk:
    name: doas
    state: present

- name: user | Install {{ usershell }}
  apk:
    name: '{{ usershell }}'
    state: present
  when: usershell not in ['ash', 'sh']

- name: user | Create {{ realtime_group }} group
  group:
    name: '{{ realtime_group }}'
    system: yes
    state: present

- name: user | Create a normal user
  user:
    name: '{{ username }}'
    password: '{{ password | password_hash("sha512") }}'
    update_password: on_create
    append: yes
    groups:
      - wheel
      - input
      - audio
      - video
      - libvirt
      - users
      - '{{ realtime_group }}'
    create_home: yes
    home: '/home/{{ username }}'
    shell: '{{ shells_list[usershell] }}'
    state: present
    comment: Kawaii Linux user

- name: user | Double check that group '{{ username }}' exists
  group:
    name: '{{ username }}'
    state: present

# We restrict /proc read permission to polkitd group
- name: user | Add the user to polkitd group
  user:
    name: '{{ username }}'
    append: yes
    groups:
      - polkitd
  when: use_polkit

- name: user | Add the user to seat group
  user:
    name: '{{ username }}'
    append: yes
    groups:
      - seat
  when: seat_manager == 'seatd'

- name: user | Ensure correct permissions for directory /etc/doas.d/
  file:
    path: /etc/doas.d
    state: directory
    owner: root
    group: root
    mode: 0750

# pm-suspend is from pm-utils package (required by libvirt-client)
- name: user | Add config for {{ username }} user to doas.conf
  blockinfile:
    path: /etc/doas.d/doas.conf
    block: |
      permit persist {{ username }}
      permit nopass {{ username }} cmd halt
      permit nopass {{ username }} cmd reboot
      permit nopass {{ username }} cmd poweroff
      permit nopass {{ username }} cmd pm-suspend
    marker: '# {mark} CUSTOM SETTINGS FOR THE NORMAL USER'
    owner: root
    group: root
    mode: 0600
    validate: /usr/bin/doas -C %s

- name: user | Add pam_limits rules for {{ realtime_group }} group
  pam_limits:
    domain: '@{{ realtime_group }}'
    limit_type: '-'
    limit_item: '{{ item.item }}'
    value: '{{ item.value }}'
    dest: '/etc/security/limits.d/95-{{ realtime_group }}.conf'
  loop: '{{ realtime_pam_limits }}'
