#!/bin/sh

default_port='8080'
default_host='localhost'
post_address_template="http://HOST:PORT/daruma"

debug="false"

daruma_client_option=''

disable_warnings='false'
stop_with_warnings='true'

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

}

file=''
ip_protocol_option=''
port="${default_port}"
host="${default_host}"

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

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

	-h|--host)
		host="${2}"

		if [ X"${disable_warnings}" != X'true' ]; then
			if echo "${host}" | grep '^[0-9]*$' 1>/dev/null; then
				echo "number only host [${host}] specified." 1>&2
				if [ X"${stop_with_warnings}" = X'true' ]; then
					exit 1
				fi
			fi
		fi

		shift 1
		;;

	-p|--port)
		port="${2}"

		if [ X"${disable_warnings}" != X'true' ]; then
			if ! echo "${port}" | grep '^[0-9]*$' 1>/dev/null; then
				echo "specified port number [${port}] includes non number character." 1>&2
				if [ X"${stop_with_warnings}" = X'true' ]; then
					exit 1
				fi
			fi
		fi

		shift 1
		;;

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

	   --debug)
		debug='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}/"`

if [ X"${debug}" = X'true' ]; then
	echo "host = [${host}]" 1>&2
	echo "port = [${port}]" 1>&2
	echo "post_address = [${post_address}]" 1>&2
	echo '--' 1>&2
fi

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