- name: Install packages
  package:
    name:
      # - linux-lts-headers
      - linux-headers
    state: present

- name: Check trusted gpg keys
  become_user: "{{ build_user.name }}"
  command: gpg --list-public-keys --keyid-format LONG
  register: gpgkeys
  changed_when: false
  check_mode: no

- name: Trust ZFS key
  when: "item not in gpgkeys.stdout"
  become_user: "{{ build_user.name }}"
  command: "gpg --recv-key '{{ item }}'"
  loop:
    - "0AB9E991C6AF658B"
    - "6AD860EED4598027"

- name: Build aur packages
  register: buildaur
  become_user: "{{ build_user.name }}"
  command: "aurutils-sync --no-view {{ item }}"
  args:
    creates: "/var/cache/pacman/custom/{{ item }}-*.pkg.tar.*"
  loop:
    - zfs-dkms-git
    - zfs-utils

- name: Update cache
  when: buildaur.changed
  pacman:
    name: []
    state: present
    update_cache: true

- name: Install packages
  package:
    name:
      - zfs-dkms-git
      - zfs-utils
    state: present

- name: Enable services
  systemd:
    enabled: yes
    name: "{{ item }}"
    daemon_reload: yes
  loop:
    - zfs-import-cache.service
    - zfs-mount.service
    - zfs.target
    - zfs-import.target

- name: Enable periodic scrub
  when: periodic_scrub_pools is defined
  systemd:
    enabled: yes
    name: "zfs-scrub-weekly@{{ item }}.timer"
    daemon_reload: yes
  loop: "{{ periodic_scrub_pools }}"

- name: Create directories
  when: periodic_scrub_pools is defined
  file:
    name: "{{ item }}"
    state: directory
    mode: 0755
    owner: root
    group: wheel # Normally it is "root"
  loop:
    - /etc/systemd/system/zfs-scrub-weekly@.timer.d

- name: Install Configuration
  when: periodic_scrub_pools is defined
  copy:
    src: "files/{{ item.src }}"
    dest: "{{ item.dest }}"
    mode: 0644
    owner: root
    group: wheel # Normally it is "root"
  loop:
    - src: linux_scrub_when_plugged_in.conf
      dest: /etc/systemd/system/zfs-scrub-weekly@.timer.d/override.conf
