## Make sure to use an initrd providing firmware:
##   wget https://cdimage.debian.org/cdimage/firmware/testing/current/firmware.cpio.gz
##   cat initrd.gz firmware.cpio.gz > initrd-fw.gz
---
- name: Install packages related to iwd and wifi
  ansible.builtin.apt:
    name:
      - iwd
      - systemd-resolved
      - firmware-realtek # for our wifi sticks
      - rfkill
    state: latest

- name: Disable wpa-supplicant
  ansible.builtin.systemd:
    name: wpa_supplicant.service
    enabled: False

- name: Enable iwd
  ansible.builtin.systemd:
    name: iwd.service
    enabled: True

- name: Prepare directory for iwd
  file:
    path: /var/lib/iwd/
    state: directory

- name: Configure iwd for wifi device
  ansible.builtin.copy:
    dest: /var/lib/iwd/{{ ssid }}.psk
    content: |
      [Security]
      Passphrase={{ wifipasswd }}

- name: Use iwd (NetworkManager)
  blockinfile:
    dest: /etc/NetworkManager/NetworkManager.conf
    block: |
      [device]
      match-device=interface-name:wl*
      wifi.backend=iwd
      [connection]
      match-device=interface-name:wl*
      ipv4.route-metric=2048

- name: Provide service to enable WiFi on boot
  ansible.builtin.copy:
    dest: /etc/systemd/system/enable-wifi.service
    content: |
      [Unit]
      Description=Switch WiFi on

      [Service]
      Type=oneshot
      ExecStart=/usr/sbin/rfkill unblock wlan

      [Install]
      WantedBy=multi-user.target
  when: not (groups.teacherlaptop is defined and inventory_hostname in groups.teacherlaptop)

- name: Enable the enable-wifi service
  ansible.builtin.systemd:
    name: enable-wifi.service
    enabled: True
    daemon_reload: True
  when: not (groups.teacherlaptop is defined and inventory_hostname in groups.teacherlaptop)
