#!/bin/sh

# Determine where this script lives and set the serverroot and the
# instanceroot variables.
instanceroot=`dirname $0`
instanceroot=`dirname ${instanceroot}`
instanceroot=`dirname ${instanceroot}`
serverroot=`dirname ${instanceroot}`

# Keep previous directory
opwd=`pwd`

# Change to lib directory since auto_ef needs files in that directory
cd ${instanceroot}/lib
charres=`$instanceroot/lib/auto_ef ${INPUT_FILE}`

# Change back to previous directory
cd $opwd

charset=""
extra=""

# check if arabic charset is detected
if [ "$charres" = "CP1256" -o "$charres" = "8859-6" -o "$charres" = "UTF-8" ]
then
	cth=`cat ${INPUT_HEADERS} | grep -i "^Content-Type:"`

	# if Content-Type header exists
	if [ -n "$cth" ]
	then
		# Get content type
		contype=`echo ${cth} | cut -d: -f2 | sed 's/^[ ]*//' | sed 's/^\([^ ;]*\)[ ;]*.*$/\1/'`

		# convert to lower case
		cth=`echo ${cth} | tr '[A-Z]' '[a-z]'`

		# Remove content type
		cth=`echo ${cth} | sed 's/^content-type:[ ]*[^ ;]*//' | sed 's/^[ ;]*//' | sed 's/[ ;]*$//'`

		# get charset
		charset=`echo ${cth} | sed 's/^.*charset[ ]*=[ ]*\([^ ;]*\).*$/\1/'`

		# pattern for removing charset
		pat="s/charset[ ]*=[ ]*[^ ;]*[; ]*//"

		# remove charset and keep the rest of the parameters
		extra=`echo ${cth} | sed "$pat"`
	else
		# if Content-Type header missing
		contype="text/plain"
	fi

	# if charset is not one of the supported arabic charset
	if [ "$charset" != "iso-8859-6" -a "$charset" != "cp1256" -a "$charset" != "utf-8" -a "$charset" != "windows-1256" ]
	then
		# Change encoding to standard name
		if [ "$charres" = "8859-6" ]
		then
			charset="ISO-8859-6"
		else
			charset="$charres"
		fi
	else
		# trust the charset sent by client
		charset=""
	fi
fi

# if charset needs to be adjusted
if [ "$charset" != "" ]
then
	# Put new "Content-Type:"
	# if extra parameters exists
	if [ -n "$extra" ]
	then
		printf "%s\n\n" "Content-Type: $contype; charset=$charset; $extra" >${OUTPUT_HEADERS}
	else
		printf "%s\n\n" "Content-Type: $contype; charset=$charset" >${OUTPUT_HEADERS}
	fi
fi

cp ${INPUT_FILE} ${OUTPUT_FILE}

exit 0
