#!/bin/busybox sh

if [ $# -ne 1 ]
then	cat <<EOT
Usage: $(basename $0) <sink-dir>
  Concatenate then delete files as soon they appear in sink-dir to stdout.
  If multiple files are found in sink, the first in alphabetical order is choosen.
  <sink-dir> must not exists, this program must create it (avoiding mistakes).
  Dropping an empty file in dir-sink will clean exit this program.
EOT
	exit 1
fi

SINKDIR=$1
mkdir "$SINKDIR" && cd "$SINKDIR"
if [ $? -ne 0 ]
then	echo "Cannot mkdir/chdir to '$SINKDIR'" >&2
	exit 2
fi

while true
do
	f=$(ls | head -n1)
	if [ -n "$f" ]
	then	if [ -f "$f" -a -r "$f" ]
		then	size=$(stat -c'%s' -- "$f")
			# Do the actual work on the following line
			cat -- "$f" && rm -v -- "$f" >&2
			# Normal exit condition
			if [ $size -eq 0 ]
			then	cd / && rmdir -v -- "$SINKDIR" >&2
				exit 0
			fi
		else	echo "'$SINKDIR/$f' is not a readable file" >&2
			exit 3
		fi
	fi
	sleep 1
done