---
- ansible.builtin.debug:
    msg: "Warning: empty 'evolinux_ssh_password_auth_addresses' variable, some configuration elements won't be set!"
  when: evolinux_ssh_password_auth_addresses == []

- name: files under /etc/ssh/sshd_config.d are included
  ansible.builtin.lineinfile:
    path: /etc/ssh/sshd_config
    line: "Include /etc/ssh/sshd_config.d/*.conf"
    insertbefore: BOF
  notify: reload ssh

- name: add SSH server configuration template
  ansible.builtin.template:
    src: sshd/defaults.j2
    dest: /etc/ssh/sshd_config.d/z-evolinux-defaults.conf
    mode: "0644"

- name: "Get current user's group"
  ansible.builtin.command:
    cmd: logname
  changed_when: False
  register: logname
  check_mode: no
  when: evolinux_ssh_allow_current_user | bool

- name: verify AllowUsers directive
  ansible.builtin.command:
    cmd: "grep -ER '^AllowUsers' /etc/ssh"
  failed_when: False
  changed_when: False
  register: grep_allowusers_ssh
  check_mode: no
  when: evolinux_ssh_allow_current_user | bool

- name: "Add AllowUsers sshd directive for current user"
  ansible.builtin.lineinfile:
    dest: /etc/ssh/sshd_config.d/allow_evolinux_user.conf
    create: yes
    line: "AllowUsers {{ logname.stdout }}"
    insertafter: 'Subsystem'
    validate: '/usr/sbin/sshd -t -f %s'
  notify: reload sshd
  when: evolinux_ssh_allow_current_user and grep_allowusers_ssh.rc != 0

- ansible.builtin.meta: flush_handlers

# TODO si allowusers et allowgroups, ajouter utilisateur aux deux
# TODO si allowgroups, ajouter groupe de l’utilisateur
