#!/bin/sh

########################################################################
#             (c) Copyright 2006 Lexmark International, Inc.           #
#                        All rights reserved                           #
########################################################################
#
#  This command is starts the main application.
#
########################################################################

#--
#-- Java VM system defines can be passed to the Java VM by specifying
#-- the defines in the VMDEFINES environment variable. To specify
#-- multiple defines, enclose the define statements in quotes. For
#-- example:
#--
#-- % export VMDEFINES="-Duser.language=de -Duser.region=DE"
#--
#--

#-- set debug to false by default. To turn debug "on" set to "1"
DEBUG=0
if [ ! -z "${SANE_DEBUG_MFP_NSCAN}" ] ;then
   DEBUG=1
fi



#-- initialize variables
APP_NAME=mfpscan
PRODUCT_LINK=/usr/mfpscan


JAR_FILE=${PRODUCT_LINK}/lib/scan.jar

if [ -x "${PRODUCT_LINK}/jre/bin/java" ];then
	JAVA_CMD=${PRODUCT_LINK}/jre/bin/java
else
	JAVA_CMD=java
fi

MAIN_TARGET="com.lexmark.unix.drivers.jscan.scan.Scan"

#-------------------------
#-- BEGIN: System Commands
#-------------------------
MORE_CMD="/bin/more"
PRINT_CMD="/bin/echo"
GREP_CMD="/bin/grep"
EGREP_CMD="/bin/egrep"
CAT_CMD="/bin/cat"
MKDIR_CMD="/bin/mkdir"
TOUCH_CMD="/bin/touch"
LS_CMD="/bin/ls"

if [ -f "/bin/awk"  ];then  AWK_CMD="/bin/awk" ; else  AWK_CMD="/usr/bin/awk"  ; fi
if [ -f "/bin/sed"  ];then  SED_CMD="/bin/sed"  ; else  SED_CMD="/usr/bin/sed"  ; fi

if [ -x "/usr/X11R6/bin/xdpyinfo" ];then XDPYINFO_CMD="/usr/X11R6/bin/xdpyinfo" ; else XDPYINFO_CMD="/usr/bin/xdpyinfo" ; fi

SYS_COMMANDS="${CAT_CMD} ${PRINT_CMD} ${PRINT_CMD} ${GREP_CMD} ${EGREP_CMD} ${MORE_CMD} ${AWK_CMD} ${SED_CMD} ${LS_CMD}"
FLAG="0"
   for i in ${SYS_COMMANDS}
   do
     if [ ! -x "${i}" ]; then
        if [ "${FLAG}" = "0" ]; then
				${PRINT_CMD}
				${PRINT_CMD} "The following system command(s) were not found:"
				${PRINT_CMD}
				FLAG="1"
        fi
        ${PRINT_CMD} "   File missing  --  $i"
     fi
   done

	if [ "${FLAG}" = "1" ]; then
      ${PRINT_CMD}
      ${PRINT_CMD} "HOW TO FIX"
      ${PRINT_CMD} "----------"
      ${PRINT_CMD} "This problem can be easily corrected by manually editing the"
      ${PRINT_CMD} "script [ ${PRODUCT_LINK}/bin/${APP_NAME} ] and modify."
      ${PRINT_CMD} "the System Commands section."
      exit 1;
   fi

#-- usage_short text
usage_short ()
{
${CAT_CMD} << EOT

USAGE:
    ${APP_NAME} --ip-address=<scanner_ip> --filename=<filename> [--debug]
    ${APP_NAME} [--help]
    ${APP_NAME} [--version]

EOT
}

#-- usage_long text
usage_long ()
{
${CAT_CMD} << EOT

${APP_NAME}
    Provides an easy way to create Scan to PC profiles.
    A scan profile includes all the necessary information about
    your documents which is send to the MFP for easy retrieval.
    The image received is an uncompresses PXM image.

USAGE:
    ${APP_NAME} --ip-address=<scanner_ipaddress> [-x]
    ${APP_NAME} [-h]
    ${APP_NAME} [-v]

OPTIONS:
    -x  Run ${APP_NAME} in debug mode.
    -h  Display this help and exit.
    -v  Display version information and exit.

FEATURES:
  Scanner:
    --ip-address
        The IP address / hostname associated with this scan job.

  Profile Information:
    --user-name
        The user name associated with this scan job.
    --profile-name
        The profile name associated with this scan job.

  Image Settings:
    --content-type
        Indicates the type of material to be scanned.
        Valid values are 0,1,2. Default value is 1.

        0 Text 
        1 Text/Graphics 
        2 Photo

    --resolution 
        The resolution of the scan job in dots per inch.
        Valid values are 75,150,200,300,400,600. Default value is 150.

    --mode 
        The color depth of the scan job.
        Valid values are 0,1,2. Default value is 1.
        
        0 1-bit Black & White
        1 8-bit Grayscale 
        2 24-bit Color

    --documentsource
        0 Black and White Laser
        1 Color Laser
        2 Inkjet Plain
        3 Inkjet Glossy
        4 Retail Photo
        5 Photo
        6 Magazine
        7 Newspaper
        8 Press
        9 General Office
       10 Auto
       11 Other

    --original-size 
        The size of the area to be scanned.
        Valid values are 0 - 26. Default value is 0.
         
        0  Letter        14 Business Card
        1  Executive     15 Book Original
        2  Legal         16 Auto Size
        3  A3            17 Mixed Size
        4  A4            18 Universal
        5  A5            19 ID Card
        6  A6            20 Oficio (México)
        7  B4            21 Custom Scan Size 1
        8  B5            22 Custom Scan Size 2
        9  Tabloid       23 Custom Scan Size 3
        10 Folio         24 Custom Scan Size 4
        11 Statement     25 Custom Scan Size 5
        12 3X5 Photo     26 Custom Scan Size 6
        13 4X6 Photo

 
    --orientation 
        The orientation of the original document text.
        Valid values are 0 and 1. Default value is 0.

        0 Portrait      
        1 Landscape 

    --scan-both-sides
        Scan both sides of the document.
        Valid values are 0 and 1. Default value is 0.

        0 no         
        1 yes

  Advanced Settings:
    --brightness
        Adjusts the brightness setting for this scan.
        Valid values are 1 - 9. Default value is 5.

    --contrast
        Adjusts the contrast setting used for this scan.
        Valid values are 0 - 5. Default value is 0.

    --bkgremoval
        Increasing background removal will make more
        light shades equal white.  Decreasing 
        background removal will preserve more light 
        shades. Valid values are -4 to 4. Default 
        value is 0.

    --mirrorimage
        Rotates scanned image horizontally.
        Valid values are 1 and 0. Default value is 0.

    --colordropout
        Removes the selected color on the scanned
        image, then returns it in gray scale or 
        black and white. Valid values are 0=None,
        1=Red, 2=Green, 3=Blue. Default value is 0.

    --colordropoutthreshold
        Works with color dropout, if color dropout 
        is equal to none, this option is inactive.
        This will control the quality of color 
        dropout. Valid values are 0 to 254. Defalut 
        value is 128.

    --negativeimage
        Inverts the pixel values. Valid values are 
        0 and 1. Default value is 0.

  Text mode:
    --text-mode 
        Launch this program in text mode.
        Valid values are 0 and 1. Default value is 0.
	     
        0 disable
        1 enable	
   
EOT

}

#--  display_version
#--
display_version()
{
   ${CAT_CMD} ${PRODUCT_LINK}/docs/version.txt
   
   ${PRINT_CMD}
}

get_cmd_option_value()
{
	var=$1
	#-- Check if interface is passed script.
	INTERFACE="`${PRINT_CMD} ${ARGS} | ${GREP_CMD} $var= 2>/dev/null`"
	if [ $? -eq 0 ];then
		for i in `${PRINT_CMD} ${ARGS}`
		do
			${PRINT_CMD} $i | ${AWK_CMD} -F= '/'$var'/ { print $2;exit 5}'
			if [ "${?}" = "5" ];then
				return 0
			fi
		done
	fi
	return 1
}
check_display()
{
	#-- Check for the xdpyinfo commmand.  
	TEXT_MODE="`${PRINT_CMD} ${ARGS} | ${GREP_CMD} text-mode=1 2>/dev/null`"
	if [ $? -eq 0 ];then
		pdebug "TEXT-MODE Enabled\n"
		return 0
	fi

	if [ -x "${XDPYINFO_CMD}" ]; then
		${XDPYINFO_CMD} >/dev/null 2>/dev/null
		if [ "${?}" != "0" ]; then
			{
				${PRINT_CMD} "MESSAGE: Error trying to open a X connection."
				${PRINT_CMD} "MESSAGE: Switching to text mode."
			} >&2
			if [ "${TEXT_MODE}" = "" ];then
				ARGS="${ARGS} --text-mode=1"
			else
				ARGS=`${PRINT_CMD} ${ARGS} | ${SED_CMD} -e 's/text-mode=0/text-mode=1/g'`
			fi
		fi
	fi
}

pdebug()
{
	if [ "${DEBUG}" = "1" ];then
		printf "${1}\n" >&2
	fi
}

license_agreement()
{
	laccept="false"

	PDHOME=`${PRODUCT_LINK}/bin/lshome`
	if [ $? -ne 0 ];then
		PDHOME=${HOME}
	fi

	USER_DIR="${PDHOME}/.${APP_NAME}"
	USER_FILE="${PDHOME}/.${APP_NAME}/LicenseAccepted"

	pdebug "\nLicense Agreement\n-----------------\nChecking for License Agreement\n"
	pdebug "FILE: ${USER_FILE}\n"

	if [ -f "${USER_FILE}" ];then
		pdebug "License Agreement has already been accepted as user. [ USER_FILE ]\n"
		return 0
	else
		pdebug "User file not found. Launch GUI.\n"
	fi

	#-- LAUNCH GUI
	LICENSE_TARGET="com.lexmark.unix.drivers.jprint.util.LicenseWindow"
	${JAVA_CMD} ${JVM_ARGS} ${VMDEFINES} -cp ${JAR_FILE} ${LICENSE_TARGET} true >&2
	JAVA_RETURN="$?"
	case "${JAVA_RETURN}" in
		0) laccept="true"
			pdebug "JAVA RETURN = ${JAVA_RETURN}\n"
			;;
		*) laccept="false"
			pdebug "JAVA RETURN = ${JAVA_RETURN}\n"
			;;
	esac

	if [ "${laccept}" = "true" ];then
		pdebug "Creating License Agreement file under user home directory.\n"
		[ ! -d "${USER_DIR}" ] && ${MKDIR_CMD} -p ${USER_DIR}
		${TOUCH_CMD} ${USER_FILE}
		return 0
	else
		exit 1
	fi
}

ARGS="${*}"
#-- parse arguments begin
while [ ! -z "${1}" ]
do
   case "$1" in
		-h|--help)
				usage_long | ${MORE_CMD}
				exit 1
				;;
		-v|-V|--version)
				display_version
				exit 1
				;;
		--debug)
				DEBUG=1
				;;
	esac
	shift 1
done

${PRINT_CMD} ${ARGS} | ${GREP_CMD} "ip-address" >/dev/null 2>&1
RC1=$?
${PRINT_CMD} ${ARGS} | ${GREP_CMD} "filename" >/dev/null 2>&1
RC2=$?
${PRINT_CMD} ${ARGS} | ${GREP_CMD} "Authorization" >/dev/null 2>&1
RC3=$?
if [ "${RC3}" != "0" ]; then
	if [ "${RC1}" != "0" ] || [ "${RC2}" != "0" ]; then
		usage_short
		exit 1
	fi
fi

check_display

# look for libXp.so* (RH5 only)
${EGREP_CMD} "Enterprise.*release 5" /etc/redhat-release >/dev/null 2>&1
if [ $? -eq 0 ];then
	XMESSAGE_CMD="/usr/bin/xmessage"
	LIBXP_ERR_MSG="
libXp.so not found!

Install libXp.rpm from your RedHat installation CD 2.

"
	${PRINT_CMD} "${ARGS}" | ${GREP_CMD} "text-mode=1" >/dev/null 2>&1
	TM=$?
	${LS_CMD} /usr/lib | ${GREP_CMD} "libXp.so" >/dev/null 2>&1

	if [ ! $? -eq 0 ];then
		if [ -x ${XMESSAGE_CMD} ] && [ ! "${TM}" = "0" ];then
			${PRINT_CMD} "${LIBXP_ERR_MSG}" | ${XMESSAGE_CMD} -file - -center
		else
			${PRINT_CMD} "${LIBXP_ERR_MSG}"
		fi
	fi

fi

# look for libXp.so* (debian5 only)
${EGREP_CMD} "5.0" /etc/debian_version >/dev/null 2>&1
if [ $? -eq 0 ];then
	XMESSAGE_CMD="/usr/bin/xmessage"
        TEMP_VALUE=0
	LIBXP_ERR_MSG="
libXp.so not found!

Install libXp from your installation CD.

"
	${PRINT_CMD} "${ARGS}" | ${GREP_CMD} "text-mode=1" >/dev/null 2>&1
	TM=$?
	${LS_CMD} /usr/lib | ${GREP_CMD} "libXp.so.6" >/dev/null 2>&1

	if [ ! $? -eq 0 ];then
          TEMP_VALUE=1
	fi
       
	${LS_CMD} /usr/lib | ${GREP_CMD} "libXp.so" >/dev/null 2>&1
	if [ ! $? -eq 0 ];then
          TEMP_VALUE=1
        else
          TEMP_VALUE=0
        fi

        if [ $TEMP_VALUE -eq 1 ]; then
		if [ -x ${XMESSAGE_CMD} ] && [ ! "${TM}" = "0" ];then
			${PRINT_CMD} "${LIBXP_ERR_MSG}" | ${XMESSAGE_CMD} -file - -center
		else
			${PRINT_CMD} "${LIBXP_ERR_MSG}"
		fi
          exit 1
        fi
fi

#-- get value of --interface
${PRINT_CMD} "${ARGS}" | ${GREP_CMD} "interface=any" >/dev/null 2>&1
RC=$?
if [ "${RC}" != "0" ];then
	value=`get_cmd_option_value interface`
	RC=$?
	if [ "${RC}" = "0" ];then
		inet=`${PRODUCT_LINK}/bin/lsinet | ${GREP_CMD} ${value} | ${AWK_CMD} -F: '{print $2}'`
		if [ ! -z "${inet}" ];then	
			ARGS=`${PRINT_CMD} ${ARGS} | ${SED_CMD} -e "s/--interface=${value}/--local-ipaddress=${inet}/g"`
		else
			ARGS=`${PRINT_CMD} ${ARGS} | ${SED_CMD} -e "s/--interface=${value}//g"`
			{	
			${PRINT_CMD} "MESSAGE:The specified interface [${value}] is not valid."
			${PRINT_CMD} "MESSAGE:Please see the configuration file for more details."
			${PRINT_CMD} "MESSAGE:Switching to default value."
		} >&2	
		fi
	fi
else
	ARGS=`${PRINT_CMD} ${ARGS} | ${SED_CMD} -e "s/--interface=any//g"`
fi

JARGS="`${PRINT_CMD} ${ARGS} | ${SED_CMD} -e 's/ --/#--/g' |  ${SED_CMD} -e 's/--//g'`"

#-- Need special Java VM flags, override the JVM_ARGS variable.
if [ -z "${JVM_ARGS}" ]; then
   #-- Set minimum VM size to 16MB set maximum to 64MB
   JVM_ARGS="-ms16m -mx64m"
fi

#-- Need special Java VM flags for languages, override the
#-- VMDEFINES variable.
if [ -z "${VMDEFINES}" ];then
	LANGUAGE="`${PRINT_CMD} ${LANG} | ${AWK_CMD} -F'_' '{print $1}' | ${SED_CMD} -e 's/\..*$//'`"
	REGION="`${PRINT_CMD} ${LANG} | ${AWK_CMD} -F'_' '{print $2}' | ${SED_CMD} -e 's/\..*$//'`"
	if [ "${REGION}" = "" ];then
		REGION="${LANGUAGE}"
	fi
	VMDEFINES="-Duser.language=${LANGUAGE} -Duser.region=${REGION} -Duser.locale=${LANG}"
	LC_ALL=${LANG}
	export LC_ALL
fi

${PRINT_CMD} "${ARGS}" | ${GREP_CMD} "text-mode=1" >/dev/null 2>&1
if [ $? -ne 0 ];then
	license_agreement
fi

if [ "${DEBUG}" = "1" ];then
	VMDEFINES="${VMDEFINES} -DDEBUG=TRUE"
	${PRINT_CMD} "${JAVA_CMD} ${JVM_ARGS} ${VMDEFINES} -cp ${JAR_FILE} ${MAIN_TARGET} \"${JARGS}\"" >&2
fi
${JAVA_CMD} ${JVM_ARGS} ${VMDEFINES} -cp ${JAR_FILE} ${MAIN_TARGET} "${JARGS}"
RC=${?}
exit $RC
