#!/bin/sh



get_default_ethernet_device() {
        LANG=C nmcli d show | awk '
                ($1 == ""){ device = 0 }
                ($1=="GENERAL.DEVICE:"){ device=$2 }
                ($1=="GENERAL.TYPE:" && $2 == "ethernet"){ print device ; exit }
        '
}

check_ethernet_device() {
        default_ethernet_device="$(get_default_ethernet_device)"
        if [ -z "$default_ethernet_device" ] ; then
                echo "No ethernet device found"
                exit 1
        fi
}

check_ethernet() {
        default_ethernet_device="$(get_default_ethernet_device)"
        if [ -z "$default_ethernet_device" ] ; then
                echo "No ethernet device found"
                exit 1
        fi
        # Test if ethernet is enabled …
        LANG=C nmcli d show "$default_ethernet_device" | awk '
                /^GENERAL.STATE:/ {
                        gsub(/^[^ ]+ +/, "", $0);
                        match($0, /^([0-9]+) \((.+)\)$/, out);
                        state_no = out[1]
                        state_text = out[2]
                }
                /^GENERAL.CONNECTION:/ {
                        gsub(/^[^ ]+ +/, "", $0);
                        connection = $0
                }
                END {
                        if (state_no == 100) {
                                print "Ethernet connected with " connection
                                exit 0
                        } else if (state_no == 30) {
                                print "Ethernet is not connected? Is it plugged in?"
                                exit 1
                        } else if (connection == "--") {
                                print "Can not connect to Ethernet: " state_text " (" state_no ")"
                                exit 1
                        } else {
                                print "Ethernet is connecting to " connection ": " state_text " (" state_no ")"
                                exit 1
                        }
                }
        '
        return $?
}


case "$1" in
	connected)
		check_ethernet ;;

	device)
		check_ethernet_device ;;
	*)
    		echo "Unknown check, use connected or device"
    		exit 1 ;;
    
esac
