# 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


- (xccdf-var var_password_pam_dcredit)



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

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

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

- name: Ensure 'pam_cracklib.so' module has conforming control flag
  ansible.builtin.lineinfile:
    path: /etc/pam.d/common-password
    regexp: '^(\s*password\s+)\S+(\s+pam_cracklib.so\s+.*)'
    line: '\g<1>requisite\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.

# NOTE(gyee): if 'var' is used, user is meant to set the argument to a
# static value

- name: Ensure "pam_cracklib.so" module has argument "dcredit={{ var_password_pam_dcredit }}"
  ansible.builtin.lineinfile:
    path: /etc/pam.d/common-password
    regexp: '^(\s*password\s+requisite\s+pam_cracklib.so(?:\s+\S+)*\s+dcredit=)(?:\S+)((\s+\S+)*\s*\\*\s*)$'
    line: '\g<1>{{ var_password_pam_dcredit }}\g<2>'
    backrefs: yes

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

- name: Add "dcredit" argument to "pam_cracklib.so" module
  ansible.builtin.lineinfile:
    path: /etc/pam.d/common-password
    regexp: '^(\s*password\s+requisite\s+pam_cracklib.so)((\s+\S+)*\s*(\\)*$)'
    line: '\g<1> dcredit={{ var_password_pam_dcredit }}\g<2>'
    backrefs: yes
  when: check_pam_module_argument_result is not skipped and '"dcredit" not in check_pam_module_argument_result.stdout'

