# platform = multi_platform_sle,multi_platform_slmicro
# reboot = false
# strategy = restrict
# complexity = low
# disruption = low

# NOTE(gyee): Ansible's pamd module is very rigid, it doesn't do
# what we wanted, which is to conditionally replace an existing value
# if it doesn't match what we wanted. Till someday some good samaritan
# updated the Ansible pamd module to do that, we will need to use regexp
# for now.


# declare the XCCDF vars if any




- name: Set control_flag fact
  ansible.builtin.set_fact:
    control_flag: 'required'

- name: Check to see if 'pam_unix.so' module is configured in '/etc/pam.d/common-auth'
  ansible.builtin.shell: |
    set -o pipefail
    grep -E '^\s*auth\s+\S+\s+pam_unix.so' /etc/pam.d/common-auth || true
  register: check_pam_module_result

- name: Configure 'pam_unix.so' module in '/etc/pam.d/common-auth'
  ansible.builtin.lineinfile:
    path: /etc/pam.d/common-auth
    line: 'auth required pam_unix.so'
    state: present
  when: check_pam_module_result.stdout is defined and '"pam_unix.so" not in check_pam_module_result.stdout'

- name: Ensure 'pam_unix.so' module has conforming control flag
  ansible.builtin.lineinfile:
    path: /etc/pam.d/common-auth
    regexp: '^(\s*auth\s+)\S+(\s+pam_unix.so\s+.*)'
    line: '\g<1>required\g<2>'
    backrefs: yes
  when: control_flag|length


# NOTE: if 'remove_argument' is present and set to some value, we assume
# user's intention is to remove the argument. Therefore, no need to check what
# it is set to.

- name: Set argument_value fact
  ansible.builtin.set_fact:
    argument_value: ""

- name: Ensure "pam_unix.so" module has argument "sha512"
  ansible.builtin.lineinfile:
    path: /etc/pam.d/common-auth
    regexp: '^(\s*auth\s+required\s+pam_unix.so(?:\s+\S+)*\s+sha512=)(?!)\S*((\s+\S+)*\s*\\*\s*)$'
    line: '\g<1>\g<2>'
    backrefs: yes
  when: argument_value|length

- name: Check the presence of "sha512" argument in "pam_unix.so" module
  ansible.builtin.shell: |
    set -o pipefail
    grep -E '^\s*auth\s+required\s+pam_unix.so.*\s+sha512(=|\s|\s*$)' /etc/pam.d/common-auth || true
  register: check_pam_module_argument_result

- name: Add "sha512" argument to "pam_unix.so" module
  ansible.builtin.lineinfile:
    path: /etc/pam.d/common-auth
    regexp: '^(\s*auth\s+required\s+pam_unix.so)((\s+\S+)*\s*(\\)*$)'
    line: '\g<1> sha512\g<2>'
    backrefs: yes
  when: check_pam_module_argument_result is not skipped and '"sha512" not in check_pam_module_argument_result.stdout'

