---
- name: Ensrue Plymouth is installed (Archlinux)
  include_tasks: plymouth-Archlinux.yml
  when: ansible_os_family == 'Archlinux'

- name: Ensure Megabyte Labs configuration directory exists
  file:
    mode: 0700
    path: "{{ item }}"
    state: directory
  loop:
    - ~/.config
    - ~/.config/megabytelabs

- name: Check if Plymouth has configuration stored in /root/.config/megabytelabs/plymouth
  stat:
    path: ~/.config/megabytelabs/plymouth
  register: plymouth_config

- name: Detect previously installed Plymouth theme
  command: cat plymouth
  args:
    chdir: ~/.config/megabytelabs
  changed_when: false
  register: current_plymouth_theme
  when: plymouth_config.stat.exists

- name: Determine whether or not to install a fresh Plymouth theme
  set_fact:
    install_plymouth_theme: "{{ (current_plymouth_theme.stdout | default('no_theme')) != plymouth_theme }}"

- name: "Ensure {{ plymouth_themes_dir }} directory exists"
  file:
    path: "{{ plymouth_themes_dir }}"
    state: directory
    mode: 0755

- name: Copy and unarchive the Plymouth theme
  unarchive:
    src: "files/plymouth-themes/{{ plymouth_theme }}.tar.gz"
    dest: "{{ plymouth_themes_dir }}"
  when: install_plymouth_theme

- name: Register the Plymouth theme
  alternatives:
    name: default.plymouth
    link: "{{ plymouth_themes_dir }}/default.plymouth"
    path: "{{ plymouth_themes_dir }}/{{ plymouth_theme }}/{{ plymouth_theme }}.plymouth"
    priority: 100
  when:
    - ansible_os_family != 'Archlinux'
    - install_plymouth_theme

- name: Activate the Plymouth theme # noqa 301
  shell: >
    set -o pipefail && echo $(echo | sudo update-alternatives --config default.plymouth
    | grep {{ plymouth_theme }} | grep -o -E '[0-9]+' | head -1 | sed -e 's/^0\\+//')
    | sudo update-alternatives --config default.plymouth
  args:
    executable: /usr/bin/bash
  notify: update initramfs
  when:
    - ansible_os_family == 'Debian'
    - install_plymouth_theme

- name: Set the Plymouth theme # noqa 301 305
  shell: plymouth-set-default-theme connect
  notify: update initramfs
  when:
    - ansible_os_family != 'Debian'
    - install_plymouth_theme

- name: Save information about the current Plymouth theme
  copy:
    dest: ~/.config/megabytelabs/plymouth
    mode: 0600
    content: |
      {{ plymouth_theme }}
  when: install_plymouth_theme
