# SPDX-License-Identifier: BSD-3-Clause
---
- name: Initialize NM profile exist and ansible_managed comment flag
  set_fact:
    lsr_net_profile_exists: false
    lsr_net_profile_ansible_managed: false
    lsr_net_profile_fingerprint: false

- name: Stat profile file
  stat:
    get_attributes: false
    get_checksum: false
    get_mime: false
    path: /etc/sysconfig/network-scripts/ifcfg-{{ profile }}
  register: profile_stat

- name: Set NM profile exist flag based on the profile files
  set_fact:
    lsr_net_profile_exists: true
  when: profile_stat.stat.exists

# When certain profile is marked as absent but still up, the `nmcli connection`
# still show it with FILENAME starting with /run. Only consider profile exists
# when its FILENAME is in /etc folder
- name: Get NM profile info
  shell: nmcli -f NAME,FILENAME connection show |grep {{ profile }} | grep /etc
  register: nm_profile_exists
  ignore_errors: true
  changed_when: false

# lsr_net_profile_ansible_managed:
# lsr_net_profile_fingerprint:
# under NetworkManager's control, the comment is not added by design.
# Thus, set it always to true.
- name: >-
    Set NM profile exist flag and ansible_managed flag true
    based on the nmcli output
  set_fact:
    lsr_net_profile_exists: true
    lsr_net_profile_ansible_managed: true
    lsr_net_profile_fingerprint: true
  when: nm_profile_exists.rc == 0

- name: Check ansible_managed comment for the initscripts case
  when:
    - profile_stat.stat.exists
    - nm_profile_exists.rc != 0
  block:
    - name: Get the ansible_managed comment in ifcfg-{{ profile }}
      command: >-
        grep "^# Ansible managed"
        /etc/sysconfig/network-scripts/ifcfg-{{ profile }}
      register: _result
      changed_when: false

    - name: Verify the ansible_managed comment in ifcfg-{{ profile }}
      set_fact:
        lsr_net_profile_ansible_managed: true
      when:
        - _result.stdout_lines | length == 1

    - name: Get the fingerprint comment in ifcfg-{{ profile }}
      command: >-
        grep "^# system_role:network"
        /etc/sysconfig/network-scripts/ifcfg-{{ profile }}
      register: _result
      changed_when: false

    - name: Verify the fingerprint comment in ifcfg-{{ profile }}
      set_fact:
        lsr_net_profile_fingerprint: true
      when:
        - _result.stdout_lines | length == 1
