---
- name: Replace NetworkManager with systemd-networkd on Fedora
  hosts: localhost
  connection: local
  become: yes
  tasks:
    - name: Stop and disable NetworkManager
      ansible.builtin.systemd:
        name: NetworkManager
        state: stopped
        enabled: no
      ignore_errors: yes

    - name: Remove NetworkManager package
      ansible.builtin.dnf:
        name: NetworkManager
        state: absent
      register: nm_remove
      ignore_errors: yes

    - name: Install systemd-networkd
      ansible.builtin.dnf:
        name: systemd-networkd
        state: present

    - name: Enable and start systemd-networkd
      ansible.builtin.systemd:
        name: systemd-networkd
        state: started
        enabled: yes

    - name: Enable and start systemd-resolved
      ansible.builtin.systemd:
        name: systemd-resolved
        state: started
        enabled: yes

    - name: Create systemd-networkd configuration directory
      ansible.builtin.file:
        path: /etc/systemd/network
        state: directory
        mode: '0755'

    - name: Configure basic DHCP network for primary interface
      ansible.builtin.copy:
        dest: /etc/systemd/network/20-wired.network
        content: |
          [Match]
          Name=en*

          [Network]
          DHCP=yes
        mode: '0644'
      notify: Restart systemd-networkd

    - name: Remove NetworkManager configuration files
      ansible.builtin.file:
        path: /etc/NetworkManager
        state: absent
      when: nm_remove.changed

    - name: Ensure systemd-resolved is linked for DNS resolution
      ansible.builtin.file:
        path: /etc/resolv.conf
        state: link
        src: /run/systemd/resolve/stub-resolv.conf
        force: yes

  handlers:
    - name: Restart systemd-networkd
      ansible.builtin.systemd:
        name: systemd-networkd
        state: restarted
