#!/bin/bash

FAILURE_GENERAL=255

osmgr=""
OPTION=""
alias=""

function updatefw() 
{
	instlmgr=""
	rpmbin=`which rpm 2>/dev/null`
	if [ $? -eq 0 ]
	then
		for file in "/etc/issue" "/etc/os-release" "/etc/redhat-release" "/etc/SuSE-release"
		do
			rpmname=`$rpmbin -qf $file 2>/dev/null`
			if [ $? -eq 0 ]
			then
				osvendor=`$rpmbin -q --qf %{VENDOR} $rpmname`
				if [ $? -eq 0 ]
				then
					osvendor=$(echo "$osvendor" | tr '[:upper:]' '[:lower:]')
					if [[ "$osvendor" =~ "redhat" || "$osvendor" =~ "red hat" || "$osvendor" =~ "rhel" || "$osvendor" =~ "centos" ]]
					then
						repomgr=`which yum 2>/dev/null`
						if [ $? -eq 0 ]
						then
								instlmgr=$repomgr
								break
						fi
					elif [[ "$osvendor" =~ "suse" || "$osvendor" =~ "sles" ]]
					then
						repomgr=`which zypper 2>/dev/null`
						if [ $? -eq 0 ]
						then
								instlmgr=$repomgr
								break
						fi
					fi
				fi
			fi
		done
	else
		echo "rpm tool is not installed on this system"
		exit $FAILURE_GENERAL
	fi

	if [ "$instlmgr" != "" ]
	then
		osmgr=$instlmgr
             	if [[ "$OPTION" =~ "-repos-to-disable=" && "$2" =~ "install" ]]
		then
		        disable_list=$OPTION
		        remove="${disable_list/-repos-to-disable=/}"
		        if [[ "$instlmgr" =~ "zypper" ]]
		        then 
				         repoalias=$(zypper repos -E)
                                         zypperrepolist=$(zypper repos)
                                         repo_list=("$(echo "$zypperrepolist" | awk '{split($0,a,"|"); print a[2]}')")
					 parse_user_repos
 
					 # disabling only the enabled repos
					 $instlmgr mr -d ${list_disabledrepo[@]} 2>/dev/null
                        elif [[ "$instlmgr" =~ "yum" ]]
                        then 
				   yumrepo=$(yum repolist enabled)
                                   yumrepolist=$(yum repolist all)
                                   repo_list=("$(echo "$yumrepolist" | awk '{split($0,a," "); print a[1]}')")
                                   parse_user_repos 
                                   yum-config-manager --disable ${list_disabledrepo[@]} 2>/dev/null
                        fi
		fi	
		requires_output=`$1 requires`
		le_exitcode=$?
		if [ $le_exitcode -eq 0 ]
		then
			for firmwaretype in $requires_output
			do
				if [[ "$2" =~ "install" ]]
				then
					echo "Installing $firmwaretype"
					$instlmgr install -y $firmwaretype
				elif [[ "$2" =~ "remove" ]]
				then
					echo "Removing $firmwaretype"
					if [[ "$instlmgr" =~ "zypper" ]]
					then
						$instlmgr remove -y $firmwaretype
					elif [[ "$instlmgr" =~ "yum" ]]
					then
						$instlmgr erase -y $firmwaretype
					else
						echo "Unknown repo manger $instlmgr"
						FAILURE_GENERAL
					fi
				fi
			done
			if [[ "$OPTION" =~ .*"-repos-to-disable=".* && ("$instlmgr" =~ "zypper" || "$instlmgr" =~ "yum") ]]
                        then
				enablerepos
			fi	
			#Exit with sum_le return code
			exit $le_exitcode
		else
			echo "Failed to run requires - $requires_output"
			#Exit with sum_le return code
			exit $le_exitcode
		fi
	else
		echo "Please install yum or zypper tool to install components "
		FAILURE_GENERAL
	fi
}
function parse_user_repos(){
                                         cached_repo_list=("$(echo "$repo_list" | cut -d'!' --output-delimiter=$'\n' -f1- )") 2>/dev/null
                                         repodisable=("$(echo "${remove[@]}" | cut -d'!' --output-delimiter=$'\n' -f1- )")
                                         listrepo=("$(echo "$repodisable" | cut -d',' --output-delimiter=$'\n' -f1- )")
                                         # identifying the not matching repos
                                         list_disabledrepo=""
                                         for user_repo in ${listrepo[@]}       #contains only user passed repo list
                                         do
                                              found_repo=""
                                              for enabled_repo in ${cached_repo_list[@]}
                                              do
                                                  if [[ "$enabled_repo" == "$user_repo" ]]
                                                  then
                                                         found_repo="true"
                                                         list_disabledrepo+=($user_repo)
                                                         break
                                                  fi
                                              done
                                              if [ -z "$found_repo" ]
                                              then
                                                    echo "No Matching repository $user_repo found."
                                                     #FAILURE_GENERAL
                                              fi
                                         done
}
function enablerepos(){
         if [[ "$OPTION" =~ .*"-repos-to-disable=".* &&  "$instlmgr" =~ "zypper" ]]
         then
                zypper_enablerepo
         elif [[ "$OPTION" =~ .*"-repos-to-disable=".* &&  "$instlmgr" =~ "yum" ]]
         then
               yum_enablerepo
         fi 
}

function zypper_enablerepo(){
 alias=("$(echo "$repoalias" | awk '{split($0,a,"|"); print a[2]}')")
 alias_catch_repo=("$(echo "$alias" | cut -d'!' --output-delimiter=$'\n' -f1- )") 2>/dev/null
 for enabled_repo in ${listrepo[@]}
 do
        for alias_repo in ${alias_catch_repo[@]}
        do
              if [[ $alias_repo == $enabled_repo ]]
              then
                      $instlmgr mr -e $enabled_repo 2>/dev/null
              fi
        done
 done
}

function yum_enablerepo(){
 yum_id=("$(echo "$yumrepo" | awk '{split($0,a," "); print a[1]}')")
 yum_cache_repo=("$(echo "$yum_id" | cut -d'!' --output-delimiter=$'\n' -f1- )") 2>/dev/null
 for yum_repo in ${listrepo[@]}
 do
      for remove_repo in ${yum_cache_repo[@]}
      do
          if [[ $remove_repo == $yum_repo ]]
          then
                  yum-config-manager --enable $yum_repo 2>/dev/null
          fi
      done
 done
}

function control_c(){
	if [[ "$OPTION" =~ .*"-repos-to-disable=".* &&  ("$osmgr" =~ "zypper" || "$osmgr" =~ "yum")  ]]
        then
		enablerepos
	fi
        exit $le_exitcode
}
trap control_c SIGINT

RUNNINGOS=$(`echo uname` | tr '[a-z]' '[A-Z]')
RUNNINGARCH=$(`echo uname -m` | tr '[a-z]' '[A-Z]')

export SUM_ROOT=""
export SUM_ARCH=""
SUM_ARCH=$RUNNINGARCH
REMOVE_LOCALPATH=0
SUM_CMD_ARGS=""

# If the TMPDIR variable is not set, use /tmp
if [ -z $TMPDIR ]; then
	TMPDIR="/tmp"
fi

FILESTAMP=`date +"%m-%d-%y-%H-%M-%S"`
SUMTMPFILE="sum-tmp-$FILESTAMP"
READONLYFS=""
FUSION_SCRIPT="${TMPDIR}/sumexecuter"

sum_return_code=$FAILURE_GENERAL

OFFLINE_MODE1=""
if [ -z $HDU_BOOTENV_SMPJTB ]; then
	OFFLINE_MODE1="."
else
	OFFLINE_MODE1=$HDU_BOOTENV_SMPJTB
	READONLYFS="yes"
fi
# echo "OFFLINE_MODE1 = $OFFLINE_MODE1"

OFFLINE_MODE2=""
if [ -z $PHOENIX ]; then
	OFFLINE_MODE2="."
else
	OFFLINE_MODE2=$PHOENIX
	READONLYFS="yes"
fi
# echo "OFFLINE_MODE2 = $OFFLINE_MODE2"

SUM_ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

if [ -f "$SUM_ROOT/$SUMTMPFILE" ] ; then
	$SUMTMPFILE="sum-tmp-$FILESTAMP-$FILESTAMP"
fi

touch "$SUM_ROOT/$SUMTMPFILE" > /dev/null 2>&1

if [ -e "$SUM_ROOT/$SUMTMPFILE" ] ; then
        rm "$SUM_ROOT/$SUMTMPFILE"
        READONLYFS="no"
else
        READONLYFS="yes"
fi

# This function copy sum executables to tmp directory and run sum from tmp directory if read-only file system found
function RunFromTmpDir() 
{
	FROMPATH=""
	if [ "$RUNNINGARCH" == "X86_64" ]; then
		FROMPATH="$BASEDIR"/x64
	else
		FROMPATH="$BASEDIR"/x86
	fi

	SUMTMPDIR="/var/tmp/localsum"
	SUM_VERSION_EXIST="no"		
	if [ -d "$SUMTMPDIR" ]; then
		SUM_VERSION_FILE=`find "$BASEDIR" -maxdepth 1 -name "sum*_b*.txt" -exec basename {} \;`
		for versionfile in $SUM_VERSION_FILE 
		do
		if [ -f "${SUMTMPDIR}"/versionfile ]; then
			SUM_VERSION_EXIST="yes"		
		else
			rm -rf $SUMTMPDIR
			break
		fi
		done
	fi	
	if [ $SUM_VERSION_EXIST == "no" ]; then	
       		echo "Copying sum files to $SUMTMPDIR"
			
	#Check to see whether mounted file system has execute permission or not.
		MOUNT_TEMPDIR=`df -P /var/tmp/ | awk 'NR==2 {print $6}'`
		result=`mount |awk ' { printf("%s|%s\n", $3, $6) } ' |grep ^$MOUNT_TEMPDIR\| | grep -i noexec`
		if [ $? -eq 0 ]; then
			echo "SUM uses $MOUNT_TEMPDIR as log directory and the $MOUNT_TEMPDIR file system doesn't have write/exec permissions"
			exit $FAILURE_GENERAL
		fi
			
        	mkdir $SUMTMPDIR
	        if [ $? -ne 0 ]; then
		        echo "Could not create the temporary directory $SUMTMPDIR"
        		exit $FAILURE_GENERAL
        	fi

        	cp -fr "$FROMPATH" $SUMTMPDIR
        	if [ $? -ne 0 ]; then
        		echo "Could not copy $FROMPATH directory to the location $SUMTMPDIR"
	                exit $FAILURE_GENERAL
        	fi
	        cp -fr "$BASEDIR"/assets $SUMTMPDIR
        	if [ $? -ne 0 ]; then
        		echo "Could not copy assets directory to the location $SUMTMPDIR"
	                exit $FAILURE_GENERAL
        	fi

			NUM_VERSION_FILES=`ls -l "$BASEDIR"/sum*_b*.txt | grep -c sum`
			if [ $NUM_VERSION_FILES -ge 1 ]; then 
					cp "$BASEDIR"/sum*_b*.txt $SUMTMPDIR
			fi

        	cp "$BASEDIR"/masterdependency.xml $SUMTMPDIR
	        if [ $? -ne 0 ]; then
        		echo "Could not copy masterdependency.xml file to the location $SUMTMPDIR"
                	exit $FAILURE_GENERAL
        	fi

        	cp "$BASEDIR"/platformdependency.xml $SUMTMPDIR
	        if [ $? -ne 0 ]; then
        		echo "Could not copy platformdependency.xml file to the location $SUMTMPDIR"
                	exit $FAILURE_GENERAL
        	fi
			
			cp "$BASEDIR"/gatherlogs.sh $SUMTMPDIR
        	if [ $? -ne 0 ]; then
        		echo "Could not copy gatherlogs.sh file to the location $SUMTMPDIR"
                	exit $FAILURE_GENERAL
        	fi

	        # copy localization files
        	cp "$BASEDIR"/*.qm $SUMTMPDIR
	fi

        # echo "executing sum_bin_<ARCH> from the location $SUMTMPDIR/<ARCH>"
	if [ "$RUNNINGARCH" == "X86_64" ]; then
        eval $SUMTMPDIR/x64/sum_bin_x64 "$@"
	else
		eval $SUMTMPDIR/x86/sum_bin_x86 "$@"
	fi
	
	sum_return_code=$?

	# remove the sum local files
	if [ ! -z $SUM_REMOVE_TEMP_FILES ]; then
		if [ "$SUM_REMOVE_TEMP_FILES" == "true" ]; then
			echo "SUM_REMOVE_TEMP_FILES set true, removing sum files"
			rm -rf $SUMTMPDIR
		fi
	fi
	
	if [ $REMOVE_LOCALPATH -eq 1 ]; then
		if [ -d "$SUMTMPDIR" ]; then
			echo "cleanup_onexit or cleanupall_onexit is set, removing sum files"
			rm -rf $SUMTMPDIR
		fi
	fi
}

function validateoption()
{
      supported_arg_list=('install' 'requires' '-repos-to-disable=' )
      supported_list=("$(echo "${supported_arg_list[@]}" | cut -d ' ' --output-delimiter=$'\n' -f1- )")
      user_listrepo=("$(echo "$@" | cut -d ' ' --output-delimiter=$'\n' -f1- )")
      for use_option in ${user_listrepo[@]}
      do
              Found_option=""
              option_value=""
              for support_option in ${supported_list[@]}
              do
                    if [[ "$use_option" =~ "$support_option" ]];then
                             Found_option="true"
                             break
                    else
                        option_value=$use_option
                    fi
              done
              if [ -z "$Found_option" ];then
                    echo "Error: cannot parse the option:"$option_value"."
                    echo "Use 'smartupdate --help' for more details on command syntax."
                    exit  $FAILURE_GENERAL
              fi
      done
}

function ParseCmdLine()
{
	#Check to see whether mounted file system has execute permission or not.
		MOUNT_TEMPDIR=`df -P /var/tmp/ | awk 'NR==2 {print $6}'`
		result=`mount |awk ' { printf("%s|%s\n", $3, $6) } ' |grep ^$MOUNT_TEMPDIR\| | grep -i noexec`
		if [ $? -eq 0 ]; then
			echo "SUM uses $MOUNT_TEMPDIR as log directory and the $MOUNT_TEMPDIR file system doesn't have write/exec permissions"
			exit $FAILURE_GENERAL
		fi
	
    ARGS=("$@")
    # get total subscripts in an array
    total=${#ARGS[*]}
   for (( i=0; i<=$(( $total -1 )); i++ ))
    do
        re="[[:space:]]+"
        if [[ ${ARGS[$i]} =~ $re ]]; then
           SUM_CMD_ARGS="$SUM_CMD_ARGS \"${ARGS[$i]}\""
        else
           SUM_CMD_ARGS="$SUM_CMD_ARGS ${ARGS[$i]}"
        fi
        #check for disable option
        if [[ ${ARGS[$i]} =~ "-repos-to-disable=" ]]
        then
            OPTION=${ARGS[$i]}
        fi
        
        if [ "${ARGS[$i]}" == "/username" -o "${ARGS[$i]}" == "-username" -o "${ARGS[$i]}" == "-user" -o "${ARGS[$i]}" == "/user" ]; then
           i=`expr $i + 1`
	   USERNAME=${ARGS[$i]}
           SUM_CMD_ARGS="$SUM_CMD_ARGS \"$USERNAME\""
	elif [ "${ARGS[$i]}" == "/passwd" -o  "${ARGS[$i]}" == "-passwd" -o  "${ARGS[$i]}" == "--passwd" ]; then
           i=`expr $i + 1`
	   PASSWORD=${ARGS[$i]}
           SUM_CMD_ARGS="$SUM_CMD_ARGS \"$PASSWORD\""
    elif [ "${ARGS[$i]}" == "/current_credential" -o "${ARGS[$i]}" == "-current_credential" ]; then
       USECURRCRED="yes"
	
    # check for use_location switch and read the path provided
    elif [ "${ARGS[$i]}" == "-use_location" -o "${ARGS[$i]}" == "/use_location" -o "${ARGS[$i]}" == "--use_location" ]; then        
        i=`expr $i + 1`
        SUM_CMD_ARGS="$SUM_CMD_ARGS \"${ARGS[$i]}\""
        USELOCATION=1

    # check for inputfile switch 
    elif [ "${ARGS[$i]}" == "-inputfile" -o "${ARGS[$i]}" == "/inputfile" -o "${ARGS[$i]}" == "--inputfile" ]; then
        i=`expr $i + 1`
        INPUTFILEPATH=${ARGS[$i]}
        SUM_CMD_ARGS="$SUM_CMD_ARGS \"$INPUTFILEPATH\""
    
    #check for help (-h, -help, --help, -?)
    elif [ "${ARGS[$i]}" == "-h" -o "${ARGS[$i]}" == "-help" -o "${ARGS[$i]}" == "--help" -o "${ARGS[$i]}" == "-?" ]; then
        HELP=1
    elif [ "${ARGS[$i]}" == "/h" -o "${ARGS[$i]}" == "/help" -o "${ARGS[$i]}" == "/?" ]; then
        HELP=1
    #check for version (-v)
    elif [ "${ARGS[$i]}" == "-v" -o "${ARGS[$i]}" == "/v" ]; then
        VERSION=1
    #check for silent (-s, -silent, --silent)
    elif [ "${ARGS[$i]}" == "-s" -o "${ARGS[$i]}" == "-silent" -o "${ARGS[$i]}" == "--silent" ]; then
        LEGACYMODE=1
    elif [ "${ARGS[$i]}" == "/s" -o "${ARGS[$i]}" == "/silent" ]; then
        LEGACYMODE=1
    elif [ "${ARGS[$i]}" == "-express_install" -o "${ARGS[$i]}" == "/express_install" ]; then
		LEGACYMODE=1
	elif [ "${ARGS[$i]}" == "-cleanup_onexit" -o "${ARGS[$i]}" == "/cleanup_onexit" ]; then
		REMOVE_LOCALPATH=1
	elif [ "${ARGS[$i]}" == "-cleanupall_onexit" -o "${ARGS[$i]}" == "/cleanupall_onexit" ]; then
		REMOVE_LOCALPATH=1
	elif echo "${ARGS[$i]}" | grep -q "logdir" || echo "${ARGS[$i]}" | grep -q "reportdir" || echo "${ARGS[$i]}" | grep -q "group" || 
	     echo "${ARGS[$i]}" | grep -q "unc_username" || echo "${ARGS[$i]}" | grep -q "vcenter_username" || echo "${ARGS[$i]}" | grep -q "oa_username" ||
		 echo "${ARGS[$i]}" | grep -q "switch_username" || echo "${ARGS[$i]}" | grep -q "switchb_username" || echo "${ARGS[$i]}" | grep -q "use_sshkey" ||
		 echo "${ARGS[$i]}" | grep -q "reboot_message" || echo "${ARGS[$i]}" | grep -q "su_username" || echo "${ARGS[$i]}" | grep -q "su_password"; then
		i=`expr $i + 1`
		SUM_CMD_ARGS="$SUM_CMD_ARGS \"${ARGS[$i]}\""
    fi
    done
}

LOG_DIR=/var/log/sum
LOG_MESG="Insufficient permissions, unable to access log directory ${LOG_DIR}"

if [ -d "${LOG_DIR}" ]; then
	#if the directory exist, then try to touch a file
	`touch ${LOG_DIR}/touched`

	if [ -f ${LOG_DIR}/touched ]; then
		`rm -fr ${LOG_DIR}/touched`
	else
		echo "${LOG_MESG}"
		exit $FAILURE_GENERAL
	fi
else
	#try to create a directory
	`mkdir -p "${LOG_DIR}"`
	if [ ! -d "${LOG_DIR}" ]; then
		echo "${LOG_MESG}"
	    exit $FAILURE_GENERAL
	fi	
fi



HPUX=`uname | grep "HP-UX"`

if [ ! -z "${HPUX}" ]; then
	HPUX=`uname -a | grep "B.11.31" | grep "ia64"`
	if [ -z "${HPUX}" ]; then
		echo "SUM HP-UX version only supports HP-UX B.11.31 ia64."
		exit $FAILURE_GENERAL
	fi
	if [ -a  ia64/sum_bin_ia64 ]; then
		ia64/sum_bin_ia64 $*
	else
		echo "Not able to find SUM client file: ia64/sum_bin_ia64"
		exit $FAILURE_GENERAL
	fi
elif [ "$RUNNINGOS" == "LINUX" ]; then
	if [ "$0" == "/sbin/smartupdate" -o "$0" == "/usr/sbin/smartupdate" ]; then
		#the script resides in the RPM installed location. 
		BASEDIR=/opt/sum/bin
		SUM_ROOT=$BASEDIR
	else
		BASEDIR=`dirname "$0"`
	fi
    export USERNAME=""
    export PASSWORD=""
    export USECURRCRED=""
  
    export INPUTFILEPATH=""
    export LEGACYMODE=0
    export USELOCATION=0
    export VERSION=0
    export HELP=0
    
    ParseCmdLine "$@"
# Check for a running sum Instance
    if [ `ps -ef | grep sum_service | grep -v "grep" | wc -l` -gt 0 ]; then
	if [ $LEGACYMODE -eq 1 ]; then
		echo An existing SUM instance is detected
		exit $FAILURE_GENERAL
	fi
    fi

    # Check to see if we should call the Firmware-RPM Wrapper
    ARGS=("$@")
    total=${#ARGS[*]}
    for (( i=0; i<=$(( $total -1 )); i++ ))
    do
		CMD=${ARGS[$i]}
		CMD_=${ARGS[$((i + 1))]}
                if [ "$RUNNINGARCH" == "X86_64" ]; then
			FWRPMCMD="$BASEDIR"/x64/sum_le_x64
		else
			FWRPMCMD="$BASEDIR"/x86/sum_le_x86
		fi

		if [[ ("$CMD" == "requires" || "$CMD" == "upgrade" || "$CMD" == "list" || "$CMD" == "info" || "$CMD" == "query" ) ]]; then
			    if [ ! -f  $FWRPMCMD ]; then
				echo "Could not find $FWRPMCMD"
				exit $FAILURE_GENERAL
			    fi
			    $FWRPMCMD "$@"
			    exit $?

                elif [[ ("$CMD" == "remove") && ("$CMD_" == "requires") ]];then
		            if [ ! -f  $FWRPMCMD ]; then
                                        echo "Could not find $FWRPMCMD"
                                        exit $FAILURE_GENERAL
                            fi
                            updatefw "$FWRPMCMD" "$@"
                            exit $?

                elif [[ ("$CMD" == "install") && ("$CMD_" == "requires") ]];then
			     if [ ! -f  $FWRPMCMD ]; then
			        	echo "Could not find $FWRPMCMD"
				        exit $FAILURE_GENERAL
			     fi
                             validateoption "$@"
                             if [ ! -z "$OPTION" ];then
                                     option_repo=("$(echo "${OPTION}" | awk '{split($0,a,"="); print a[1]}')")
                                     option_list=("$(echo "${OPTION}" | awk '{split($0,a,"="); print a[2]}')")
		                     if [[ "$CMD" == "install" && (("$option_repo" != "" && "$option_repo" != "-repos-to-disable") || ("$option_repo" == "-repos-to-disable" && "$option_list" == ""))  ]];then
				             echo "Invalid option, run command as smartupdate install requires -repos-to-disable=<repo1>,<repo2>"
                                             exit $FAILURE_GENERAL
                                     fi
                             fi
			     updatefw "$FWRPMCMD" "$@"
			     exit $?
		fi

    done
    # Invoke the proper version of sum_bin
	if [ "$RUNNINGARCH" == "X86_64" ]; then
	    if [ -a  "$BASEDIR"/x64/sum_bin_x64 ]; then
		 		PACKAGES_DIR=""
		 		if [ $OFFLINE_MODE1 == "yes" ]; then
					PACKAGES_DIR=`pwd`
					READONLYFS="yes" 

					# Do not copy SUM to /tmp if it is fusion mode
					if [ -f $FUSION_SCRIPT ]; then
						PACKAGES_DIR="."
						READONLYFS="no"
					fi
		 		elif [ $OFFLINE_MODE2 == 1 ]; then
					PACKAGES_DIR=`pwd`
					READONLYFS="yes"

					# Do not copy SUM to /tmp if it is fusion mode
					if [ -f $FUSION_SCRIPT ]; then
						PACKAGES_DIR="."
						READONLYFS="no"
					fi
		 		else
					PACKAGES_DIR="."
		 		fi

				if [ $READONLYFS == "yes" ]; then
                    if [ $VERSION -eq 1 -o $HELP -eq 1 ]; then
                        PACKAGES_DIR="."
                    elif [ $USELOCATION -ne 1 -a $LEGACYMODE -eq 1 ]; then
						SUM_ROOT=\"$SUM_ROOT\"
                        SUM_CMD_ARGS="$SUM_CMD_ARGS -use_location $SUM_ROOT"
                        PACKAGES_DIR=`pwd`
                    else
                        PACKAGES_DIR=`pwd`
                    fi
                fi

		 		if [ "$PACKAGES_DIR" == "." ]; then
                    eval "$BASEDIR/x64/sum_bin_x64 $SUM_CMD_ARGS"
                    sum_return_code=$?
		 		else
					RunFromTmpDir "$SUM_CMD_ARGS"
				fi
	    else
	        echo "Could not find SUM client file: x64/sum_bin_x64"
		exit $FAILURE_GENERAL
	    fi
	else
	    if [ -a  "$BASEDIR"/x86/sum_bin_x86 ]; then
			if [ $READONLYFS == "yes" ]; then
                if [ $VERSION -eq 1 -o $HELP -eq 1 ]; then
                    eval "$BASEDIR/x86/sum_bin_x86 $SUM_CMD_ARGS"
                    sum_return_code=$?
                elif [ $USELOCATION -ne 1 -a $LEGACYMODE -eq 1 ]; then
                    SUM_CMD_ARGS="$SUM_CMD_ARGS -use_location $SUM_ROOT"
                    RunFromTmpDir $SUM_CMD_ARGS
                else
                    RunFromTmpDir $SUM_CMD_ARGS
                fi
			else
				eval "$BASEDIR/x86/sum_bin_x86 $SUM_CMD_ARGS"
				sum_return_code=$?
			fi
	    else
	        echo "Could not find SUM client file: x86/sum_bin_x86"
			exit $FAILURE_GENERAL
	    fi
	fi

	exit $sum_return_code
else
	echo "SUM not supported on $RUNNINGOS"
	exit $FAILURE_GENERAL
fi



