# 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_delay)



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

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

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

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

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

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

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

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

