#!/bin/bash

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

export HPSUM_ROOT=""
export HPSUM_ARCH=""
HPSUM_ARCH=$RUNNINGARCH

HPSUM_CMD_ARGS="$@"

FILESTAMP=`date +"%m-%d-%y-%H-%M-%S"`
HPSUMTMPFILE="hpsum-tmp-$FILESTAMP"
READONLYFS=""
FUSION_SCRIPT="/tmp/hpsumexecuter"

FAILURE_GENERAL=255

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"

function CheckAndInstallToolsForGaius()
{
	PREINSTALLDIR=`echo $0 | sed "s|\(.*\)/\(.*\)|\1|"`/../preinstaller

	if [ -d "$PREINSTALLDIR" ]; then
	# Iterate on all the scexe files and run them
	# These files will:
	#	install rpm tool on the gaius/altair environment
		for ALTAIRTOOLFILE in "$PREINSTALLDIR"/*.scexe
		do
			# echo "Executing the file $ALTAIRTOOLFILE"
			$ALTAIRTOOLFILE
			RC=$?

			# returns a 2 if the file does not apply to the current environment
			# return 1 if the execution fails

			if [ $RC -eq 1 ]; then
				echo "Altair file $ALTAIRTOOLFILE execution failed with return code [$RC] !!";
				exit $FAILURE_GENERAL
			fi
		done
	fi
}

# Kick off the Altair SCEXE files before starting HPSUM application
# Must be done before first use of 'dirname'
if [ $OFFLINE_MODE1 == "yes" ] || [ $OFFLINE_MODE2 == 1 ]; then
	CheckAndInstallToolsForGaius
fi

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

if [ -f "$HPSUMTMPFILE" ] ; then
        HPSUMTMPFILE="hpsum-tmp-$FILESTAMP-$FILESTAMP"
fi

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

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

# This function copy hpsum executables to tmp directory and run hpsum 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

	DATESTRING=`date +"%m-%d-%y-%H-%M-%S"`
        HPSUMTMPDIR="/tmp/hpsum-$DATESTRING"
        echo "Copying hpsum files to $HPSUMTMPDIR"
        mkdir $HPSUMTMPDIR
        if [ $? -ne 0 ]; then
	        echo "Could not create the temporary directory $HPSUMTMPDIR"
        	exit $FAILURE_GENERAL
        fi

        cp -fr $FROMPATH $HPSUMTMPDIR
        if [ $? -ne 0 ]; then
        	echo "Could not copy $FROMPATH directory to the location $HPSUMTMPDIR"
                exit $FAILURE_GENERAL
        fi
        cp -fr $BASEDIR/assets $HPSUMTMPDIR
        if [ $? -ne 0 ]; then
        	echo "Could not copy assets directory to the location $HPSUMTMPDIR"
                exit $FAILURE_GENERAL
        fi
        cp $BASEDIR/masterdependency.xml $HPSUMTMPDIR
        if [ $? -ne 0 ]; then
        	echo "Could not copy masterdependency.xml file to the location $HPSUMTMPDIR"
                exit $FAILURE_GENERAL
        fi
		cp $BASEDIR/gatherlogs.sh $HPSUMTMPDIR
        if [ $? -ne 0 ]; then
        	echo "Could not copy gatherlogs.sh file to the location $HPSUMTMPDIR"
                exit $FAILURE_GENERAL
        fi

        # copy localization files
        cp $BASEDIR/*.qm $HPSUMTMPDIR

        # echo "executing hpsum_bin_<ARCH> from the location $HPSUMTMPDIR/<ARCH>"
	if [ "$RUNNINGARCH" == "X86_64" ]; then
        	eval $HPSUMTMPDIR/x64/hpsum_bin_x64 "$@"
	else
		eval $HPSUMTMPDIR/x86/hpsum_bin_x86 "$@"
	fi
}

function ParseCmdLine()
{
    ARGS=("$@")
    # get total subscripts in an array
    total=${#ARGS[*]}
   for (( i=0; i<=$(( $total -1 )); i++ ))
    do
        if [ "${ARGS[$i]}" == "/username" -o "${ARGS[$i]}" == "-username" ]; then
           i=`expr $i + 1`
	   USERNAME=${ARGS[$i]}
	elif [ "${ARGS[$i]}" == "/passwd" -o  "${ARGS[$i]}" == "-passwd" ]; then
           i=`expr $i + 1`
	   PASSWORD=${ARGS[$i]}
	elif [ "${ARGS[$i]}" == "/su_username" -o "${ARGS[$i]}" == "-su_username" ]; then
           i=`expr $i + 1`
	elif [ "${ARGS[$i]}" == "/su_password" -o "${ARGS[$i]}" == "-su_password" ]; then
           i=`expr $i + 1`
    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" ]; then        
        USELOCATION=1

    # check for inputfile switch 
    elif [ "${ARGS[$i]}" == "-inputfile" -o "${ARGS[$i]}" == "/inputfile" ]; then
        i=`expr $i + 1`
        INPUTFILEPATH=${ARGS[$i]}
    
    #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
    fi
    done
}

LOG_DIR=/var/hp/log
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 "HPSUM HP-UX version only supports HP-UX B.11.31 ia64."
		exit $FAILURE_GENERAL
	fi
	if [ -a  ia64/hpsum_bin_ia64 ]; then
		ia64/hpsum_bin_ia64 $*
	else
		echo "Not able to find HPSUM client file: ia64/hpsum_bin_ia64"
		exit $FAILURE_GENERAL
	fi
elif [ "$RUNNINGOS" == "LINUX" ]; then
	if [ $0 == "/sbin/hpsum" -o $0 == "/usr/sbin/hpsum" ]; then
		#the script resides in the RPM installed location. 
		BASEDIR=/opt/hp/hpsum/bin
		HPSUM_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 hpsum Instance
    if [ `ps -ef | grep hpsum_service | grep -v "grep" | wc -l` -gt 0 ]; then
	if [ $LEGACYMODE -eq 1 ]; then
		echo An existing HP 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
	    for (( j = 0; j < $i; j++))
	    do
		shift
	    done

	    if [ "$RUNNINGARCH" == "X86_64" ]; then
	        FWRPMCMD=$BASEDIR/x64/hp-sum
	    else
	        FWRPMCMD=$BASEDIR/x86/hp-sum
	    fi

	    if [ -a  $FWRPMCMD ]; then
		    $FWRPMCMD "$@"
	        exit $?
	    else
	        echo "Could not find $FWRPMCMD"
		exit $FAILURE_GENERAL
	    fi
	fi
    done

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

					# Do not copy HP 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 HP 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
                        HPSUM_CMD_ARGS="$HPSUM_CMD_ARGS -use_location $HPSUM_ROOT"
                        PACKAGES_DIR=`pwd`
                    else
                        PACKAGES_DIR=`pwd`
                    fi
                fi

		 		if [ $PACKAGES_DIR == "." ]; then
                    eval $BASEDIR/x64/hpsum_bin_x64 $HPSUM_CMD_ARGS
		 		else
					RunFromTmpDir $HPSUM_CMD_ARGS
				fi
	    else
	        echo "Could not find HPSUM client file: x64/hpsum_bin_x64"
		exit $FAILURE_GENERAL
	    fi
	else
	    if [ -a  $BASEDIR/x86/hpsum_bin_x86 ]; then
			if [ $READONLYFS == "yes" ]; then
                if [ $VERSION -eq 1 -o $HELP -eq 1 ]; then
                    eval $BASEDIR/x86/hpsum_bin_x86 $HPSUM_CMD_ARGS
                elif [ $USELOCATION -ne 1 -a $LEGACYMODE -eq 1 ]; then
                    HPSUM_CMD_ARGS="$HPSUM_CMD_ARGS -use_location $HPSUM_ROOT"
                    RunFromTmpDir $HPSUM_CMD_ARGS
                else
                    RunFromTmpDir $HPSUM_CMD_ARGS
                fi
			else
				eval $BASEDIR/x86/hpsum_bin_x86 $HPSUM_CMD_ARGS
			fi
	    else
	        echo "Could not find HPSUM client file: x86/hpsum_bin_x86"
		exit $FAILURE_GENERAL
	    fi
	fi
else
	echo "HPSUM not supported on $RUNNINGOS"
	exit $FAILURE_GENERAL
fi
