#!/bin/bash

EXPECTED_NEW_ID="dummy1-new"

nmcli c del dummy1 2>/dev/null || true
nmcli c del $EXPECTED_NEW_ID 2>/dev/null || true

NM_DBUS_CMD="/usr/lib64/qt5/bin/qdbus \
    --system org.freedesktop.NetworkManager"
NM_DBUS_CMDL="/usr/lib64/qt5/bin/qdbus --literal \
    --system org.freedesktop.NetworkManager"

rpm -q qt5-qttools 1>/dev/null 2>/dev/null
if [ $? -ne 0 ];then
    dnf install -y qt5-qttools
fi

function get_connection_id() {
    local iface_name=$1

    for dev in $($NM_DBUS_CMDL |grep 'Devices/'); do
        local dev_name=$($NM_DBUS_CMD $dev \
            org.freedesktop.NetworkManager.Device.Interface)
        if [ "CHK$dev_name" == "CHK$iface_name" ];then
            echo $($NM_DBUS_CMDL $dev \
                org.freedesktop.NetworkManager.Device.GetAppliedConnection \
                0,0 | sed -ne 's/.\+"id" = [^"]\+"\([^"]\+\)"].\+/\1/p')
        fi
    done
}

nmcli c add type dummy ifname dummy1 connection.id dummy1 \
    ipv4.method disabled ipv6.method disabled

OLD_ID=$(get_connection_id dummy1)

echo "Old applied connection ID is '${OLD_ID}'"

nmcli c modify dummy1 connection.id $EXPECTED_NEW_ID
nmcli d reapply dummy1

NEW_ID=$(get_connection_id dummy1)
echo "New applied connection ID is '${NEW_ID}'"

if [ "CHK$NEW_ID" != "CHK$EXPECTED_NEW_ID" ];then
    echo "FAILED: expected '${EXPECTED_NEW_ID}', got '$NEW_ID'"
    exit 1
else
    echo "PASS: expected '${EXPECTED_NEW_ID}', got '$NEW_ID'"
fi
