#!/bin/bash

set_ENV() {

# 	UTRACE="0 10M 0"
# 	UOBJDUMP="0 100k 10"
#	export UTRACE UOBJDUMP

	DOC_PARSE=../../../../examples/doc_parse/doc_parse

	export DOC_PARSE TBOTE DOC_TAG
}

write_OUTPUT() {

	if [ -n "$1" ]; then

		echo -e "Content-Type: text/html; charset=iso-8859-1\r\n\r"
		echo -n -E "$1"

		exit 0

	fi
}

extract_doc_tag() {

	# -----------------------------------------------------------------------------------------------------
	# check for file name -> ../tmp/fd9a6604-3e12-404c-8d8e-570b90d1735b.eml_1.1.2
	#																		         TBOTE.eml_  TAG
	# -----------------------------------------------------------------------------------------------------

	TAG=$(echo $1 | cut -f2 -d'_')

	if [ "$TAG" != "$1" ]; then

		TBOTE=$(echo $1 | cut -f1 -d'_')

		TBOTE=$(basename $TBOTE)

		DOC_TAG=$(basename $1).$2

	else

		TBOTE=$(basename $1)

		DOC_TAG=$TBOTE"_"$2

	fi

	if [ "$2" == "1.1.1" -o ! -f "../tmp/$DOC_TAG" ]; then

		$DOC_PARSE -e $2 $1 > ../tmp/$DOC_TAG

	fi
}

view_doc_tag() {

	extract_doc_tag $1 $2

   echo -e "X-Sendfile: doc_parse/tmp/$DOC_TAG\r\n\r"

	exit 0
}

exec_doc_parse() {

	if [ -n "$DOC_TAG" ]; then

		DIR=tmp

	else

		TBOTE=$1

		DIR=storage

		DOC_TAG=$TBOTE

	fi

	if [ -f "../storage/$TBOTE" ]; then

		OUTPUT=`$DOC_PARSE -H ../$DIR/$DOC_TAG`

	else

		# NOT FOUND

		echo -e "Status: 404\r\n\r\n" \
				  "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n" \
				  "<html><head>\r\n" \
				  "<title>404 Not Found</title>\r\n" \
				  "</head><body>\r\n" \
				  "<h1>Not Found</h1>\r\n" \
				  "<p>The requested TBOTE $TBOTE was not found on this server.<br />\r\n" \
				  "</p>\r\n" \
				  "<hr>\r\n" \
				  "<address>ULib Server</address>\r\n" \
				  "</body></html>\r"

		exit 0

	fi
}

view_doc() {

	# -----------------------------------------------------------------------------------------------------
	# check for file name -> fd9a6604-3e12-404c-8d8e-570b90d1735b_edb5939401225000e01500fac0a8dc0_1.1.2.eml
	#																		  TBOTE_                  SUB_FOLDER_ID_  TAG.eml
	# -----------------------------------------------------------------------------------------------------

	TAG=$(echo $1 | cut -f3 -d'_')

	if [ "$TAG" != "$1" ]; then

		TAG=$(basename $TAG .eml)

		TBOTE=$(echo $1 | cut -f1 -d'_').eml

		extract_doc_tag ../storage/$TBOTE $TAG

	fi

	exec_doc_parse "$1"
}
