# platform = multi_platform_ol,multi_platform_rhel,multi_platform_almalinux
# reboot = false
# strategy = configure
# complexity = low
# disruption = low

{{% set usbguard_config_path = "/etc/usbguard/rules.conf" %}}

- name: Generate USBGuard Policy
  block:
  - name: Gather the package facts
    ansible.builtin.package_facts:
      manager: auto

  - name: Check that the {{{ usbguard_config_path }}} exists
    ansible.builtin.stat:
      path: "{{{ usbguard_config_path }}}"
    register: policy_file

  - name: Create USBGuard Policy configuration
    ansible.builtin.command: usbguard generate-policy
    register: policy
    when: not policy_file.stat.exists or policy_file.stat.size == 0

  - name: Copy the Generated Policy configuration to a persistent file
    ansible.builtin.copy:
      content: "{{ policy.stdout }}"
      dest: "{{{ usbguard_config_path }}}"
      mode: 0600
    when: not policy_file.stat.exists or policy_file.stat.size == 0

  - name: Add comment into {{{ usbguard_config_path }}} when system has no USB devices
    ansible.builtin.lineinfile:
      path: "{{{ usbguard_config_path }}}"
      line: "# No USB devices found"
      state: present
    when: not policy_file.stat.exists or policy_file.stat.size == 0

{{%- if init_system == "systemd" %}}
  - name: Enable service usbguard
    ansible.builtin.systemd:
      name: "usbguard"
      enabled: "yes"
      state: "started"
      masked: "no"
  when: '"usbguard" in ansible_facts.packages'
{{%- else %}}
JINJA TEMPLATE ERROR: Unknown init system '{{{ init_system }}}'
{{%- endif %}}
