---
- hosts: all
  vars:
    __sshd_test_backup_files:
      - /etc/ssh/sshd_config
      - /etc/ssh/sshd_config.d/00-ansible_system_role.conf
      - /tmp/ssh_host_rsa_key2
  tasks:
    - name: "Backup configuration files"
      ansible.builtin.include_tasks: tasks/backup.yml

    - name: Remove host key before the test
      ansible.builtin.file:
        path: /tmp/ssh_host_rsa_key2
        state: absent

    - name: Ensure group 'nobody' exists
      ansible.builtin.group:
        name: nobody

    - name: Ensure the user 'nobody' exists
      ansible.builtin.user:
        name: nobody
        group: nobody
        comment: nobody
        create_home: no
        shell: /sbin/nologin

    - name: Configure sshd with alternative host keys
      ansible.builtin.include_role:
        name: redhat.rhel_system_roles.sshd
      vars:
      # very BAD example
        sshd_hostkey_owner: "nobody"
        sshd_hostkey_group: "nobody"
        sshd_hostkey_mode: "0664"
        sshd:
          HostKey:
            - /tmp/ssh_host_rsa_key2

    - name: Verify the options are correctly set
      block:
        - name: Flush handlers
          ansible.builtin.meta: flush_handlers

        - name: Print current configuration file
          ansible.builtin.slurp:
            src: "{{ main_sshd_config }}"
          register: config

        - name: Get stat of private key
          ansible.builtin.stat:
            path: /tmp/ssh_host_rsa_key2
          register: privkey

        - name: Get stat of public key
          ansible.builtin.stat:
            path: /tmp/ssh_host_rsa_key2.pub
          register: pubkey

        - name: Check the options are in configuration file
          ansible.builtin.assert:
            that:
              - "'HostKey /tmp/ssh_host_rsa_key2' in config.content | b64decode"

        - name: Check the generated host key has requested properties
          ansible.builtin.assert:
            that:
              - privkey.stat.exists
              - privkey.stat.gr_name == 'nobody'
              - privkey.stat.pw_name == 'nobody'
              - privkey.stat.mode == '0664'
              - pubkey.stat.exists
      tags: tests::verify

    - name: "Restore configuration files"
      ansible.builtin.include_tasks: tasks/restore.yml
