#!/bin/sh



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

check_wifi_device() {
        default_wifi_device="$(get_default_wifi_device)"
        if [ -z "$default_wifi_device" ] ; then
                echo "No wifi device found"
                exit 1
        fi
}

check_wifi_enabled() {
        if ! nmcli r wifi | grep -q '^enabled$' ; then
                echo "WiFi device is disabled ($(nmcli r wifi))"
                exit 1
        fi
}

check_wifi() {
        default_wifi_device="$(get_default_wifi_device)"
        if [ -z "$default_wifi_device" ] ; then
                echo "No wifi device found"
                exit 1
        fi
        # Test if wifi is enabled …
        LANG=C nmcli d show "$default_wifi_device" | awk '
                /^GENERAL.STATE: +[0-9]+ / {
                        gsub(/^[^ ]+ +/, "", $0);
                        match($0, /^[0-9]+ \((.+)\)$/);
                        state_no = $1
                        gsub(/^[0-9]+ \(/, "", $0)
                        gsub(/\)$/, "", $0)
                        state_text = $0
                }
                /^GENERAL.CONNECTION:/ {
                        gsub(/^[^ ]+ +/, "", $0);
                        connection = $0
                }
                END {
                        if (state_no == 100) {
                                print "WiFi connected with " connection
                                exit 0
                        } else if (state_no == 30) {
                                print "WiFi is not connected? Is the router in range?"
                                exit 1
                        } else if (connection == "--") {
                                print "Can not connect to WiFi: " state_text " (" state_no ")"
                                exit 1
                        } else {
                                print "WiFi is connecting to " connection ": " state_text " (" state_no ")"
                                exit 1
                        }
                }
        '
        return $?
}


case "$1" in
	connected)
		check_wifi ;;

	enabled)
		check_wifi_enabled ;;

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