- name: SSH Daemon Configuration
  block:
    - name: Install OpenSSH server
      ansible.builtin.apt:
        name: openssh-server
        state: present

    - name: Create sshusers group for SSH access control
      ansible.builtin.group:
        name: sshusers
        state: present

    - name: Add user to sshusers group
      ansible.builtin.user:
        name: "{{ user_name }}"
        groups: sshusers
        append: true

    - name: Add root to sshusers group
      ansible.builtin.user:
        name: root
        groups: sshusers
        append: true

    - name: Create SSH login banner
      ansible.builtin.copy:
        content: "{{ ssh_banner_content }}"
        dest: /etc/issue.net
        mode: "0644"

    - name: Add new user's SSH public key
      ansible.posix.authorized_key:
        user: "{{ user_name }}"
        state: present
        key: "{{ lookup('file', ssh_public_key_path) }}"

    - name: Use custom sshd_config
      ansible.builtin.template:
        src: templates/sshd_config.j2
        dest: /etc/ssh/sshd_config
        mode: "0600"
        validate: "/usr/sbin/sshd -t -f %s"
      notify: Restart sshd

    - name: Output configured SSH port
      ansible.builtin.debug:
        msg: "SSH port configured: {{ ssh_port }}"

- name: Validate SSH connection before closing ports
  ansible.builtin.include_tasks: validate.yml
