---

# this check must be repeated for each user
# even if it's been done before
- name: verify AllowUsers directive
  ansible.builtin.command:
    cmd: "grep -E '^AllowUsers' /etc/ssh/sshd_config"
  changed_when: False
  failed_when: False
  check_mode: no
  register: grep_allowusers_ssh

- name: "Add AllowUsers sshd directive with '{{ user.name }}'"
  ansible.builtin.lineinfile:
    dest: /etc/ssh/sshd_config
    line: "\nAllowUsers {{ user.name }}"
    insertafter: 'Subsystem'
    validate: '/usr/sbin/sshd -t -f %s'
  notify: reload sshd
  when: grep_allowusers_ssh.rc != 0

- name: "Append '{{ user.name }}' to AllowUsers sshd directive"
  ansible.builtin.replace:
    dest: /etc/ssh/sshd_config
    regexp: '^(AllowUsers ((?!\b{{ user.name }}\b).)*)$'
    replace: '\1 {{ user.name }}'
    validate: '/usr/sbin/sshd -t -f %s'
  notify: reload sshd
  when: grep_allowusers_ssh.rc == 0

- name: "verify Match User directive"
  ansible.builtin.command:
    cmd: "grep -E '^Match User' /etc/ssh/sshd_config"
  changed_when: False
  failed_when: False
  check_mode: no
  register: grep_matchuser_ssh

- name: "Add Match User sshd directive with '{{ user.name }}'"
  ansible.builtin.lineinfile:
    dest: /etc/ssh/sshd_config
    line: "\nMatch User {{ user.name }}\n    PasswordAuthentication no"
    insertafter: "# END EVOLINUX PASSWORD RESTRICTIONS BY ADDRESS"
    validate: '/usr/sbin/sshd -t -f %s'
  notify: reload sshd
  when: grep_matchuser_ssh.rc != 0

- name: "Append '{{ user.name }}' to Match User's sshd directive"
  ansible.builtin.replace:
    dest: /etc/ssh/sshd_config
    regexp: '^(Match User ((?!{{ user.name }}).)*)$'
    replace: '\1,{{ user.name }}'
    validate: '/usr/sbin/sshd -t -f %s'
  notify: reload sshd
  when: grep_matchuser_ssh.rc == 0
