# This file is part of bish-bosh. It is subject to the licence terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/raphaelcohn/bish-bosh/master/COPYRIGHT. No part of bish-bosh, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
# Copyright © 2014-2015 The developers of bish-bosh. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/raphaelcohn/bish-bosh/master/COPYRIGHT.


core_usesIn bishbosh/connection validate
core_usesIn bishbosh/connection/write CONNECT DISCONNECT PINGREQ PUBACK PUBCOMP PUBLISH PUBREC PUBREL SUBSCRIBE UNSUBSCRIBE

core_dependency_oneOf '*' dd cat tee tail head tr
bishbosh_connection_write_initialise()
{	
	if core_compatibility_whichNoOutput dd; then
		bishbosh_connection_write_file()
		{
			dd if="$1" bs=$2 count=1
		}
	elif core_compatibility_whichNoOutput cat; then
		bishbosh_connection_write_file()
		{
			cat "$1"
		}
	elif core_compatibility_whichNoOutput tee; then
		bishbosh_connection_write_file()
		{
			tee <"$1"
		}
	elif core_compatibility_whichNoOutput tail; then
		bishbosh_connection_write_file()
		{
			tail -c +0 "$1"
		}
	elif core_compatibility_whichNoOutput head; then
		bishbosh_connection_write_file()
		{
			head -c "$1"
		}
	elif core_compatibility_whichNoOutput tr; then
		bishbosh_connection_write_file()
		{
			# BusyBox doesn't like tr '' ''
			tr -d '' <"$1"
		}
	else
		core_message WARN "Can not write message and password files, because dd, cat, tee, head and tr are missing"
		bishbosh_connection_write_file()
		{
			core_exitError $core_commandLine_exitCode_OSFILE "Can not send files as messages or passwords, because dd, cat, tee, head and tr are missing"
		}
	fi
}

bishbosh_connection_write_byte()
{
	printf "\\$(printf '%o' $1)"
}

bishbosh_connection_write_remainingLength()
{
	if [ $1 -lt 128 ]; then
		bishbosh_connection_write_byte $1
	elif [ $1 -lt 16384 ]; then
		local length=$1
		bishbosh_connection_write_byte $(( length % 128 + 128 ))
		bishbosh_connection_write_byte $(( length / 128))
	elif [ $1 -lt 2097152 ]; then
		local length=$1
		bishbosh_connection_write_byte $(( (length & 127) + 128 ))
		bishbosh_connection_write_byte $(( (length >> 7 & 127) + 128 ))
		bishbosh_connection_write_byte $((  length >> 14 & 127 ))
	else
		local length=$1
		bishbosh_connection_write_byte $(( (length & 127) + 128 ))
		bishbosh_connection_write_byte $(( (length >> 7 & 127) + 128 ))
		bishbosh_connection_write_byte $(( (length >> 14 & 127) + 128 ))
		bishbosh_connection_write_byte $((  length >> 21 & 127 ))
	fi
}

bishbosh_connection_write_twoByteLength()
{
	local length=$1
	bishbosh_connection_write_byte $(( length >> 8 ))
	bishbosh_connection_write_byte $(( length & 255 ))
}
