---
- name: apparmor | Install apparmor and default profiles
  apk:
    name: apparmor, apparmor-profiles
    state: present

- name: apparmor | Enable writing cache and faster DFA transition table compression
  lineinfile:
    path: /etc/apparmor/parser.conf
    state: present
    search_string: '{{ item }}'
    line: '{{ item }}'
    owner: root
    group: root
    mode: 0644
  loop:
    - write-cache
    - Optimize=compress-fast

# Don't start it yet, as it requires the kernel parameters
- name: apparmor | Add apparmor service to runlevel 'boot'
  service:
    name: apparmor
    runlevel: boot
    enabled: yes

- name: apparmor | Check whether apparmor kernel parameters is presented
  lineinfile:
    backup: yes
    path: /etc/default/grub
    regexp: '^GRUB_CMDLINE_LINUX_DEFAULT=".*apparmor=.*'
    state: absent
  check_mode: yes
  register: apparmor_cmdline_check
  changed_when: no

- name: apparmor | Add apparmor to grub boot command if missing
  lineinfile:
    backrefs: yes
    path: /etc/default/grub
    regexp: '^(GRUB_CMDLINE_LINUX_DEFAULT=".*)"$'
    line: '\1 apparmor=1 security=apparmor"'
    owner: root
    group: root
    mode: 0644
  when: apparmor_cmdline_check.found == 0
  notify: Update grub config
