#!/usr/bin/env bash
# initialize a semaphore with a given number of tokens
open_sem(){
	mkfifo pipe-$$
	exec 3<>pipe-$$
	rm pipe-$$
	local i=$1
	for((;i>0;i--)); do
		printf %s 000 >&3
	done
}

# run the given command asynchronously and pop/push tokens
run_with_lock(){
	local x
	# this read waits until there is something to read
	read -u 3 -n 3 x && ((0==x)) || exit $x
	(
		( "$@"; )
		# push the return code of the command to the semaphore
		printf '%.3d' $? >&3
	)&
}

# number of concurrent jobs
open_sem 256

SECONDS=0

while read line
do
	run_with_lock curl http://s3.uni-plovdiv.net/gs/nodes/API-ethernet-bulk.php --data-binary "$line"
done < $1

# wait for all jobs to finish
wait

echo "Finished bulk import in $SECONDS seconds."
