---
- name: Ensure Users are Configured Correctly
  user:
    name: "{{ item.value.name }}"
    group: "{{ item.value.group }}"
    groups: "{{ item.value.groups }}"
    state: "{{ item.value.state }}"
    create_home: "{{ item.value.create_home }}"
    shell: "{{ item.value.shell }}"
  loop: "{{ init_users | dict2items }}"

- name: Create or ensure presence of custom home directories
  file:
    path: /home/opal/{{ item }}
    state: directory
    mode: '0755'
    owner: opal
    group: opal
  loop: "{{ create_directories }}"

- name: Remove default home directories if present
  file:
    path: /home/opal/{{ item }}
    state: absent
  loop: "{{ remove_directories }}"

# SSH Initial Setup
- name: Create/Ensure ~/.ssh directories
  file:
    path: "/home/{{ item.value.name }}/.ssh"
    state: directory
    mode: 0700
    owner: "{{ item.value.name }}"
    group: "{{ item.value.group }}"
  loop: "{{ init_users | dict2items }}"

- name: Upgrade all packages
  package:
    name: "*"
    state: latest

- name: Add Ubuntu PPAs to apt repositories
  apt_repository:
    repo: "{{ item }}"
    codename: "jammy"   # Force the Ubuntu codename that PPAs support (e.g., "focal" or "jammy")
    state: present
  loop: "{{ ppa }}"

- name: Install window manager packages
  package:
    name: "{{ item }}"
    state: present
  loop: "{{ wm_packages }}"

- name: Install UI/Font packages
  package:
    name: "{{ item }}"
    state: present
  loop: "{{ ui_packages }}"

- name: Install general packages
  package:
    name: "{{ item }}"
    state: present
  loop: "{{ general_packages }}"

- name: Install Doom Emacs dependency packages
  package:
    name: "{{ item }}"
    state: present
  loop: "{{ doom_dep_packages }}"

- name: Add Flathub repository
  flatpak_remote:
    name: flathub
    state: present
    flatpakrepo_url: "https://flathub.org/repo/flathub.flatpakrepo"

- name: doom emacs repo
  become: yes
  become_user: opal
  git:
    repo: "{{ doom_emacs_repo }}"
    dest: "{{ doom_emacs_dest }}"
    update: no

- name: et-book font repo
  become: yes
  become_user: opal
  git:
    repo: "{{ etbook_repo }}"
    dest: "{{ etbook_dest }}"
    update: no

- name: Start TLP (power management)
  systemd:
    name: tlp
    enabled: yes
    state: started

- name: Add rsync backup job to cron
  cron:
    name: "Backup KeePassXC database to desktop"
    minute: "0"
    hour: "10"
    day: "*"
    month: "*"
    weekday: "*"
    job: "/usr/bin/rsync -avz /home/opal/documents/keepassxc/opalkeepassxc.kdbx opal@desktop:/home/opal/documents"
