---
- name: usbguard | Install usbguard
  community.general.apk:
    name: usbguard
    state: present

- name: usbguard | Allow normal user to control policy via IPC
  lineinfile:
    path: /etc/usbguard/usbguard-daemon.conf
    regexp: '^IPCAllowedUsers='
    line: 'IPCAllowedUsers=root {{ username }}'
    state: present
    owner: root
    group: root
    mode: '600'

- name: usbguard | Start usbguard service on runlevel 'default'
  service:
    name: usbguard
    runlevel: default
    enabled: true
    state: started

- name: usbguard | Check whether there are defined policies
  stat:
    path: /etc/usbguard/rules.conf
  register: have_policies

# Or else you will be locked out from your desktop with no keyboards and mice
- name: usbguard | Generate policies for currently connected devices
  shell: /usr/bin/usbguard generate-policy > /etc/usbguard/rules.conf
  args:
    removes: /usr/bin/usbguard
  when: have_policies.stat.size == 0

- name: usbguard | Ensure correct permissions for /etc/usbguard/rules.conf
  file:
    path: /etc/usbguard/rules.conf
    owner: root
    group: root
    mode: '600'

- name: usbguard | Restart usbguard service to apply appended policies
  service:
    name: usbguard
    runlevel: default
    state: restarted
