# platform = multi_platform_all
# reboot = false
# strategy = configure
# complexity = low
# disruption = medium
- name: "Test for domain group"
  ansible.builtin.command: grep '^\s*\[domain\/[^]]*]' /etc/sssd/sssd.conf
  register: test_grep_domain
  failed_when: false
  changed_when: False
  check_mode: no

- name: "Add default domain group (if no domain there)"
  community.general.ini_file:
    path: /etc/sssd/sssd.conf
    section: "{{ item.section }}"
    option: "{{ item.option }}"
    value: "{{ item.value }}"
    create: yes
    mode: 0600
  with_items:
    - { section: sssd, option: domains, value: default}
    - { section: domain/default, option: id_provider, value: files }
  when:
    - test_grep_domain.stdout is defined
    - test_grep_domain.stdout | length < 1

- name: "Enable Smartcards in SSSD"
  community.general.ini_file:
    dest: /etc/sssd/sssd.conf
    section: pam
    option: pam_cert_auth
    value: 'True'
    create: yes
    mode: 0600

- name: Find all the conf files inside /etc/sssd/conf.d/
  ansible.builtin.find:
    paths: "/etc/sssd/conf.d/"
    patterns: "*.conf"
  register: sssd_conf_d_files

- name: Fix pam_cert_auth configuration in /etc/sssd/conf.d/
  ansible.builtin.replace:
    path: "{{ item.path }}"
    regexp: '[^#]*pam_cert_auth.*'
    replace: 'pam_cert_auth = True'
  with_items: "{{ sssd_conf_d_files.files }}"

{{% if product in ["fedora", "ol8", "ol9"] or 'rhel' in product %}}
- name: '{{{ rule_title }}} - Check if system relies on authselect'
  ansible.builtin.stat:
    path: /usr/bin/authselect
  register: result_authselect_present

- name: '{{{ rule_title }}} - Remediate using authselect'
  block:
    {{{ ansible_enable_authselect_feature('with-smartcard', rule_title=rule_title) | indent(4) }}}
  when:
    - result_authselect_present.stat.exists

- name: '{{{ rule_title }}} - Remediate by directly editing PAM files'
  block:
    {{{ ansible_ensure_pam_module_option('/etc/pam.d/smartcard-auth', 'auth', 'sufficient', 'pam_sss.so', 'allow_missing_name', '', '', rule_id=rule_id, rule_title=rule_title) | indent(4) }}}
    {{{ ansible_ensure_pam_module_option('/etc/pam.d/system-auth', 'auth', '[success=done authinfo_unavail=ignore ignore=ignore default=die]', 'pam_sss.so', 'try_cert_auth', '', '', rule_id=rule_id, rule_title=rule_title) | indent(4) }}}
  when:
    - not result_authselect_present.stat.exists
{{% endif %}}
