---
- name: Read salt from environment
  ansible.builtin.set_fact:
    user_password_salt: "{{ lookup('env', 'USER_PASSWORD_SALT') | default('') }}"

- name: Adding ssh users
  become: true
  ansible.builtin.user:
    name: "{{ item.username }}"
    comment: "{{ item.comment }} ( Managed by ansible )"
    password: "{{ lookup('env', 'USER_PASSWORD_' + (item.username | upper)) | password_hash('sha512', user_password_salt) }}"
    state: "{{ 'absent' if item.enabled is defined and not item.enabled else 'present' }}"
    shell: "{{ item.shell if item.shell is defined else '/bin/bash' }}"
  loop: "{{ login_users }}"

- name: Disable password expiration
  ansible.builtin.command: chage -M -1 "{{ item.username }}"
  become: yes
  when: item.password_expiration is defined and not item.password_expiration
  loop: "{{ login_users }}"

- name: Disable password login
  ansible.builtin.command: passwd -d "{{ item.username }}"
  become: yes
  when: item.password_disabled is defined and item.password_disabled
  loop: "{{ login_users }}"

- name: "Add SSH Authorized key"
  become: true
  ansible.posix.authorized_key:
    user: "{{ item.username }}"
    key: "{{ item.pubkey }}"
    state: "{{ 'present' if item.pubkey is defined else 'absent' }}"
  when: item.pubkey is defined
  loop: "{{ login_users }}"

- name: Create sudoers.d entry if user allowed
  become: true
  ansible.builtin.copy:
    dest: "/etc/sudoers.d/{{ item.username }}"
    content: |
      {{ item.username }} ALL=({{ 'root' if item.sudoer_root_only is defined and item.sudoer_root_only  else 'ALL' }}) {{ 'NOPASSWD:' if item.sudoer_no_password is defined and item.sudoer_no_password else '' }}ALL
    owner: root
    group: root
    mode: "0600"
  when: item.sudoer is defined and item.sudoer
  loop: "{{ login_users }}"

- name: Disable user history
  become: true
  ansible.builtin.copy:
    dest: "/etc/profile.d/disable_history.sh"
    content: |
      #!/bin/bash
      readonly PROMPT_COMMAND='history -a'
      readonly HISTFILE=/dev/null
    owner: root
    group: root
    mode: "0755"
