---
- name: Create groups
  group:
    name: "{{ item }}"
    state: present
  loop: "{{ init_groups }}"

- 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: Create or ensure presence of custom files
  file:
    path: /home/opal/{{ item }}
    state: touch
    mode: '0644'
    owner: opal
    group: opal
  loop: "{{ create_files }}"

- 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: Install galaxy collections
  community.general.ansible_galaxy_install:
    type: collection
    name: "{{ item }}"
  loop: "{{ ansible_galaxy_collections }}"

- name: Mask wpa_supplicant service
  systemd:
    name: wpa_supplicant
    enabled: no
    masked: yes
    state: stopped

- name: Ensure NetworkManager is enabled at boot
  systemd:
    name: NetworkManager
    enabled: yes

- name: Configure NetworkManager to manage all interfaces
  template:
    src: templates/NetworkManager.conf.j2
    dest: /etc/NetworkManager/NetworkManager.conf
    owner: root
    group: root
    mode: '0644'
  notify: Restart NetworkManager

- name: Install iwd
  apt:
    name: iwd
    state: present
    update_cache: yes

- name: Configure NetworkManager to use iwd
  copy:
    dest: /etc/NetworkManager/conf.d/wifi_backend.conf
    content: |
      [device]
      wifi.backend=iwd
  notify: Restart NetworkManager
