# platform=multi_platform_all
# reboot = false
# strategy = configure
# complexity = low
# disruption = low

{{% set find_command_base = 'find -H /etc/ssh/ -maxdepth 1 -user root -regex ".*_key$" -type f' %}}
{{% set dedicated_ssh_groupname = groups.get("dedicated_ssh_keyowner", {}).get("name") %}}

{{% if product in ["ol9", "sle12", "sle15", "slmicro5", "slmicro6"] %}}
{{% set find_command_permissions = 'u+xs,g+xws,o+xwrt' %}}
{{% set permissions_mode = 'u-xs,g-xws,o-xwrt' %}}
{{% else %}}
{{% set find_command_permissions = 'u+xs,g+xwrs,o+xwrt' %}}
{{% set permissions_mode = 'u-xs,g-xwrs,o-xwrt' %}}
{{% endif %}}

- name: Find root:root-owned keys
  ansible.builtin.command: '{{{ find_command_base }}} -group root -perm /{{{ find_command_permissions }}}'
  register: root_owned_keys
  changed_when: False
  failed_when: False
  check_mode: no

- name: Set permissions for root:root-owned keys
  ansible.builtin.file:
    path: "{{ item }}"
    mode: '{{{ permissions_mode }}}'
    state: file
  with_items:
    - "{{ root_owned_keys.stdout_lines }}"

{{% if dedicated_ssh_groupname -%}}
- name: Find root:{{{ dedicated_ssh_groupname }}}-owned keys
  ansible.builtin.command: '{{{ find_command_base }}} -group {{{ dedicated_ssh_groupname }}} -perm /u+xs,g+xws,o+xwrt'
  register: dedicated_group_owned_keys
  changed_when: False
  failed_when: False
  check_mode: no

- name: Set permissions for root:{{{ dedicated_ssh_groupname }}}-owned keys
  ansible.builtin.file:
    path: "{{ item }}"
    mode: "u-xs,g-xws,o-xwrt"
    state: file
  with_items:
    - "{{ dedicated_group_owned_keys.stdout_lines }}"
{{%- endif %}}
