get_machine_type() {
	grep "^machine" /proc/cpuinfo | cut -f 2- -d ":" | sed 's/^ *//'
}


_get_or_set_gpio() {
	local pin="$1"
	local value="${2:-}"
	local gpio_path="/sys/class/gpio/gpio$pin"
	# setup
	if [ ! -d "$gpio_path" ]; then
		echo "$pin" >/sys/class/gpio/export
		# wir muessen nach der Initialisierung kurz warten
		sleep 1
		echo out >"$gpio_path/direction"
		sleep 1
	fi
	if [ -n "$value" ]; then
		# neuen Zustand setzen
		echo "$value" >"$gpio_path/value"
	else
		local state=$(cat "$gpio_path/value")
		# aktuellen Zustand zurueckliefern
		[ "$state" = "1" ] && return 0 || return 1
	fi
}


_get_poe_passthrough_function() {
	local machine_type=$(get_machine_type)
	if [ "$machine_type" = "TP-LINK CPE210/220/510/520" ]; then
		echo "_get_or_set_gpio 20"
	elif [ "$machine_type" = "Ubiquiti Nanostation M" ]; then
		# Nanostation XM: loco oder HP
		# leider koennen wir sie nicht unterscheiden
		echo "_get_or_set_gpio 8"
	elif [ "$machine_type" = "Ubiquiti Nanostation M XW" ]; then
		# die HP-Variante (anstelle von "Ubiquiti Loco M XW")
		echo "_get_or_set_gpio 2"
	else
		# keine POE-Unterstuetzung
		true
	fi
}


has_poe_passthrough_support() {
	local funcname=$(_get_poe_passthrough_function)
	[ -z "$funcname" ] && return 1
	return 0
}


get_poe_passthrough_state() {
	local funcname=$(_get_poe_passthrough_function)
	[ -z "$funcname" ] && msg_error "POE passthrough is not supported for this device." && return 0
	$funcname
}


disable_poe_passthrough() {
	local funcname=$(_get_poe_passthrough_function)
	[ -z "$funcname" ] && msg_error "POE passthrough is not supported for this device." && return 0
	$funcname 0
}


enable_poe_passthrough() {
	local funcname=$(_get_poe_passthrough_function)
	[ -z "$funcname" ] && msg_error "POE passthrough is not supported for this device." && return 0
	$funcname 1
}
