http_post() {
	if [ $# != 2 ]; then
		echo "Usage: http_post <url> <data>" 1>&2
		return 255
	fi
	command="${HTTP_CLIENT#*=}"
	case "${HTTP_CLIENT%%=*}" in
		wget)
			[ -z "$command" ] && command=wget
			"$command" --no-verbose "$1" --post-data "$2"
			;;
		curl)
			[ -z "$command" ] && command=curl
			"$command" "$1" --request POST --data-binary "$2"
			;;
		netcat)
			echo "FIXME" 1>&2
			return 1
			;;
		bash)
			echo "FIXME" 1>&2
			return 1
			;;
	esac
}

get_ip_address() {
	if [ $# != 1 ]; then
		echo "Usage: get_ip_address <interface>" 1>&2
		return 255
	fi
	ifconfig "$1" | grep -Eo -m 1 'inet[ a-z:]+172\.20\.0\.[0-9]{3}' | sed -r 's/^inet[ a-z:]+//'
	return 0
}

set_hostname_from_interface() {
	HOSTNAME="`get_ip_address \"$1\"`"
	if [ -z "$HOSTNAME" ]; then
		printf "Cannot get IP address from interface '%s'\\n" "$1" 1>&2
		exit 1
	fi
}

load_config_file() {
	[ -f "$1" ] || return
	eval "`grep -Eo '^[A-Z0-9_]+=[-A-Za-z0-9_@" .:/\\]+' \"$1\"`"
}

handle_command_line_options() {
	while getopts i:I:n: c
	do case "$c" in
		i)
			INTERVAL="$OPTARG"
			;;
		I)
			INTERFACE="$OPTARG"
			;;
		n)
			HOSTNAME="$1"
			;;
		\?)
			printf "Usage: %s [-i <interval>] [-I <interface>] [-n <hostname>]\\n" "$0" 1>&2
			exit 255
			;;
	esac done
}

check_http_client() {
	if wget --version 2> /dev/null | grep -q "^GNU Wget "; then
		HTTP_CLIENT=wget
	elif curl --version 2> /dev/null | grep -q "^curl "; then
		HTTP_CLIENT=curl
	elif printf %s "$INFLUXDB_BASE_URL" | grep -q "^http://"; then
		if ncat --version 2>&1 | grep -q "^Ncat: "; then
			HTTP_CLIENT=netcat=ncat
		else
			for nc in netcat nc; do case "`$nc --version 2>&1 | sed 1!d`" in
				"Ncat: "*|*"The GNU Netcat"*)
					HTTP_CLIENT=netcat=$nc
					return
					;;
			esac done
			if nc -h 2>&1 | grep -Eq '^\[v1\..+\]$'; then
				HTTP_CLIENT=netcat=nc
			elif [ -n "$BASH" ]; then
				HTTP_CLIENT=bash
			else
				echo "Need a HTTP client tool to post data via HTTP" 1>&2
				exit 1
			fi
		fi
	else
		echo "Need a HTTP client tool to post data via HTTPS" 1>&2
		echo "Please install wget(1) or curl(1)" 1>&2
		exit 1
	fi
}
