---
- name: APT install
  ansible.builtin.apt:
    cache_valid_time: 3600
    install_recommends: false
    name:
      - alsa-utils
      - avahi-daemon
      - desktop-base
      - flatpak
      - plymouth-label
      - plymouth-themes
      - firmware-linux
      - udisks2
      - unison
      - upower
      - xorg
    state: present
    update_cache: true

- name: Configure boot splash
  ansible.builtin.copy:
    backup: true
    content: |
      [Daemon]
      Theme=homeworld
    dest: /etc/plymouth/plymouthd.conf
    mode: 0o0644
  notify:
    - Rebuild initramfs

- name: Enable boot splash
  ansible.builtin.lineinfile:
    backup: true
    # yamllint disable-line rule:line-length
    line: GRUB_CMDLINE_LINUX_DEFAULT="quiet splash systemd.unified_cgroup_hierarchy=0"
    path: /etc/default/grub
  notify:
    - Update GRUB

- name: Create library mountpoint
  ansible.builtin.file:
    mode: 0o0755
    path: /srv/library
    state: directory

- name: Mount library
  ansible.posix.mount:
    backup: true
    fstype: auto
    opts: defaults,nofail
    path: /srv/library
    src: UUID=ed8e28fd-3d7d-4daa-b85c-71e5a721e0f6
    state: mounted
  notify: Restart Kodi

- name: Add Flatpak remotes
  with_dict:
    flathub: https://flathub.org/repo/flathub.flatpakrepo
  community.general.flatpak_remote:
    flatpakrepo_url: '{{ item.value }}'
    method: system
    name: '{{ item.key }}'
    state: present

- name: Install Flatpak
  community.general.flatpak:
    method: system
    name: tv.kodi.Kodi
    remote: flathub
    state: present

- name: Create users
  loop:
    - kodi
    - transmission
  loop_control:
    index_var: idx
  ansible.builtin.user:
    create_home: true
    home: /var/lib/{{ item }}
    name: '{{ item }}'
    password: '!'  # pragma: allowlist secret
    shell: /bin/false
    state: present
    system: true
    uid: '{{ 900 + idx }}'
  notify:
    - Restart Xorg
    - Restart Kodi

- name: Configure rootless Xorg
  ansible.builtin.copy:
    backup: true
    content: |
      allowed_users=anybody
    dest: /etc/X11/Xwrapper.config
    mode: 0o0644
  notify:
    - Restart Xorg

- name: Copy services
  with_items: &services
    - xorg.service
    - kodi.service
  ansible.builtin.copy:
    dest: /etc/systemd/system/
    mode: preserve
    src: '{{ item }}'
  notify:
    - Restart Xorg
    - Restart Kodi

- name: Enable services
  with_items: *services
  ansible.builtin.service:
    daemon-reload: true
    enabled: true
    name: '{{ item }}'
    state: started

- name: Allow access to Kodi's webui from Docker containers
  community.general.ufw:
    from: 172.16.0.0/12
    proto: tcp
    rule: allow
    to_port: !!str 8080
