#  Copyright 2022 Dell Inc. or its subsidiaries. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
---

- name: Check if AllowUsers entry exixts
  shell: cat "{{ sshd_conf_file }}"
  register: file_content
  changed_when: false

- name: Check if user is specified
  debug:
    msg: "Users not specified"
  when: user | length < 1

- name: Configure sshd_config
  block:
    - name: Configure sshd_config file when AllowUsers entry not exists
      lineinfile:
        path: "{{ sshd_conf_file }}"
        line: 'AllowUsers {{ user }}'
      notify:
        - Restart sshd
      when:
        - allow_deny == 'Allow'
        - file_content.stdout.find('AllowUsers') == -1

    - name: Configure sshd_config file when DenyUsers entry not exists
      lineinfile:
        path: "{{ sshd_conf_file }}"
        line: 'DenyUsers {{ user }}'
      notify:
        - Restart sshd
      when:
        - allow_deny == 'Deny'
        - file_content.stdout.find('DenyUsers') == -1

    - name: Configure sshd_config file when AllowUsers entry exists
      replace:
        path: "{{ sshd_conf_file }}"
        regexp: '^(AllowUsers)(.*)'
        replace: '\1\2 {{ user }}'
      notify:
        - Restart sshd
      when:
        - allow_deny == 'Allow'
        - file_content.stdout.find('AllowUsers') != -1

    - name: Configure sshd_config file when DenyUsers entry exists
      replace:
        path: "{{ sshd_conf_file }}"
        regexp: '^(DenyUsers)(.*)'
        replace: '\1\2 {{ user }}'
      notify:
        - Restart sshd
      when:
        - allow_deny == 'Deny'
        - file_content.stdout.find('DenyUsers') != -1

  when:
    - user | length > 1