#!/bin/sh

port='8080'
host='localhost'
post_address_template="http://HOST:PORT/daruma"

debug_http_post='false'

daruma_client_option=''

usage()
{
	echo "Usage: ${0} [option ...] FILE"
	echo "Possible options are:"
	echo "     --help"
	echo " -h, --host HOST"
	echo " -p, --port PORT"
	echo " -4, --ipv4-only"
}

file=""
ip_protocol_options=""

while [ "${#}" -gt 0 ]
do
	case "${1}" in

	--help)
		usage 1>&2
		exit 0
		;;

	-h|--host)
		host="${2}"
		shift 1
		;;

	-p|--port)
		port="${2}"
		shift 1
		;;

	-4|--ipv4-only)
		ip_protocol_options="-4"
		;;

	   --debug)
		debug_http_post='true'
		;;

	-*)
		usage 1>&2
		echo 1>&2
		echo "unknown option: ${1}" 1>&2
		exit 1
		;;

	*)
		if [ ! -z "${file}" ]; then
			echo 'multiple file specified' 1>&2
			exit 1
		fi
		file="${1}"
		;;
	esac

	shift 1
done


if [ -z "${file}" ]; then
	usage 1>&2
	exit 1
fi

size=`cat "${file}" | LC_ALL=C LANG=C wc -c | sed 's/ //g'`

post_address=`echo "${post_address_template}" \
		| sed "s/HOST/${host}/" \
		| sed "s/PORT/${port}/"`

(echo "POST ${post_address} HTTP/1.1"; \
 echo "Host: ${host}"; \
 echo "Content-length: ${size}"; \
 echo; \
 cat "${file}") \
  | if [ X"${debug_http_post}" = X'true' ]; then
	tee /dev/stderr
    else
	cat
    fi \
  | darumaClient $daruma_client_option $ip_protocol_options \
	    -h "${host}" -p "${port}"
