#!/bin/bash

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"

FAILURE_GENERAL=255
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 "$SUMTMPFILE" ] ; then
        SUMTMPFILE="sum-tmp-$FILESTAMP-$FILESTAMP"
fi

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

if [ -e "$SUMTMPFILE" ] ; then
        rm $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"
	
        	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 ParseCmdLine()
{
    ARGS=("$@")
    # get total subscripts in an array
    total=${#ARGS[*]}
   for (( i=0; i<=$(( $total -1 )); i++ ))
    do
        SUM_CMD_ARGS="$SUM_CMD_ARGS ${ARGS[$i]}"
        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]}
        if [ "$CMD" == "requires" -o "$CMD" == "upgrade" -o "$CMD" == "list" -o "$CMD" == "info" -o "$CMD" == "query" ]; then

	    if [ "$RUNNINGARCH" == "X86_64" ]; then
	        FWRPMCMD="$BASEDIR"/x64/sum_le_x64
	    else
	        FWRPMCMD="$BASEDIR"/x86/sum_le_x86
	    fi

	    if [ -a  $FWRPMCMD ]; then
		    $FWRPMCMD "$@"
	        exit $?
	    else
	        echo "Could not find $FWRPMCMD"
		exit $FAILURE_GENERAL
	    fi
	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


