---
- name: Configure network settings
  become: true
  block:
    - name: Install systemd-networkd on Rocky
      ansible.builtin.dnf:
        name: systemd-networkd
        state: present

    - name: Ensure network config directory exists
      ansible.builtin.file:
        path: /etc/systemd/network
        state: directory
        owner: root
        group: root
        mode: 0755

    - name: Create network files
      ansible.builtin.template:
        src: network.j2
        dest: /etc/systemd/network/{{ item.key }}.network
        mode: 0644
        owner: root
        group: "{{ ansible_user }}"
      loop: "{{ skylab_networking | dict2items }}"
      loop_control:
        label: "{{ item.key }}"

    - name: Create netdev files
      when: item.value.device is defined
      ansible.builtin.template:
        src: netdev.j2
        dest: /etc/systemd/network/{{ item.key }}.netdev
        mode: 0644
        owner: root
        group: "{{ ansible_user }}"
      loop: "{{ skylab_networking | dict2items }}"
      loop_control:
        label: "{{ item.key }}"

    - name: Fetch existing network config directory contents
      changed_when: false
      ansible.builtin.command:
        cmd: /usr/bin/ls /etc/systemd/network
      register: _network_config_dir_raw

    - name: Remove legacy network config files
      when: item.strip().replace('.netdev', '').replace('.network', '') not in skylab_networking
      ansible.builtin.file:
        path: /etc/systemd/network/{{ item }}
        state: absent
      loop: "{{ _network_config_dir_raw.stdout_lines }}"
      loop_control:
        label: "{{ item.strip() }}"

    - name: Configure fallback DNS
      ansible.builtin.lineinfile:
        path: /etc/systemd/resolved.conf
        create: false
        line: FallbackDNS=

    - name: Enable systemd-networkd
      ansible.builtin.systemd:
        name: "{{ item }}"
        enabled: true
      loop:
        - systemd-networkd
        - systemd-networkd-wait-online
        - systemd-resolved

    - name: Disable NetworkManager
      ansible.builtin.systemd:
        name: "{{ item }}"
        enabled: false
      loop:
        - NetworkManager
        - NetworkManager-wait-online

    - name: Start systemd-resolved to enable symlink creation
      ansible.builtin.systemd:
        name: systemd-resolved
        state: started

    - name: Link system resolv.conf to systemd-resolved
      ansible.builtin.file:
        dest: /etc/resolv.conf
        src: /run/systemd/resolve/resolv.conf
        state: link
        force: true
        setype: net_conf_t

    - name: Link systemd-resolved to multi-user target
      ansible.builtin.file:
        dest: /etc/systemd/system/multi-user.target.wants/systemd-resolved.service
        src: /usr/lib/systemd/system/systemd-resolved.service
        state: link
        force: true
