# 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.


# The form $'\t' does not work in dash
bishbosh_connection_read_controlpacket_SUBACK_separator="$(printf '\t')"
core_dependency_declares bishbosh_connection_read_controlpacket_SUBACK_separator

core_dependency_requires '*' rm
bishbosh_connection_read_controlpacket_SUBACK()
{
	local packetIdentifier
	bishbosh_connection_read_packetIdentifier
	
	local ourPacketIdentifierFolderPath
	bishbosh_connection_packetIdentifier_ourPacketIdentifierFolderPath
	
	local unknownPacketIdentifier
	if [ -f "$ourPacketIdentifierFolderPath"/subscribe ]; then
		unknownPacketIdentifier=0
	else
		unknownPacketIdentifier=1
		
		core_message WARN "Received a SUBACK with packet identifier '$packetIdentifier' for a SUBSCRIBE that doesn't appear to be ours'"
	fi
	
	local returnCodeCount=$((remainingLength-2))
	if [ $returnCodeCount -eq 0 ]; then
		bishbosh_connection_error_protocolReadControlPacket SUBACK "Received no return codes"
	fi

	local topicFiltersPath="$ourPacketIdentifierFolderPath"/topic-filters
	if [ -d "$topicFiltersPath"/"$(printf '%09s' $returnCodeCount)" ]; then
		bishbosh_connection_error_protocolReadControlPacket SUBACK "Received too few return codes '$returnCodeCount'"
	fi
	
	set --
	
	local topicFiltersPath="$ourPacketIdentifierFolderPath"/topic-filters
	local returnCode
	local index=0
	while [ $index -ne $returnCodeCount ]
	do
		if [ ! -d "$topicFiltersPath"/"$(printf '%09s' $index)" ]; then
			bishbosh_connection_error_protocolReadControlPacket SUBACK "Received too many return codes '$returnCodeCount' (request '$index' does not exist)"
		fi
		
		bishbosh_connection_read_byte_blocking returnCode
		
		case $returnCode in
		
			0|1|2|128)
				IFS=' ' set -- "$@" $returnCode
			;;
		
			*)
				bishbosh_connection_error_protocolReadControlPacket SUBACK "Received reserved returnCode code of '$returnCode' in zero-based position '$index'"
			;;
		
		esac
		
		index=$((index+1))
	done
	
	bishbosh_connection_handler_SUBACK "$@"
	
	bishbosh_connection_packetIdentifier_retireOneOfOurs
}
