#!/bin/sh
# Copyright (c) 2009-2013 Intel Corporation. All rights reserved.
# This script installs Intel(R) VTune(TM) Amplifier XE 2013 for Linux*.





CONFIG_CLEAR() {

    local prefix="$1"

    PREFIXEDVARS=$(set | egrep "^$prefix");
    for PREFIXEDVAR in $PREFIXEDVARS; do
        VARNAME=$(echo $PREFIXEDVAR | cut -d "=" -f1);
        eval "unset $VARNAME"
    done;

} # function config_clear



CONFIG_READ_FILE() {

    LOG_ARGS "$@"
    local clear="yes"

    while [ -n "$(echo "$1" | egrep '^\-[a-zA-Z]$')" ]; do
        case "$1" in
            -C ) clear="no";;
            *  ) CROAK "$FUNCNAME(): illegal option: $1";;
        esac
        shift 1
    done

    [ $# -eq 2 ] || CROAK "$FUNCNAME() expects 2 arguments"

    local prefix="$1"
    local file="$2"

    [ -e "$file" ] || DIE "File \"$file\" does not exist."
    [ -f "$file" ] || DIE "\"$file\" is not a file."
    [ -r "$file" ] || DIE "File \"$file\" is not readable."

    [ "yes" = "$clear" ] && CONFIG_CLEAR "$prefix"

    local i=0
    local section
    local name
    local value
    while read line; do
        i=$(( $i + 1 ))
        if [ -n "$(echo "$line" | egrep '^#')" ]; then
            : # Skip comments
        elif [ -n "$(echo "$line" | egrep "^\[[_0-9a-zA-Z]+\]$")" ]; then
            section="$(echo "$line" | tr -d '][')" # Strip brackets
        elif [ -n "$(echo "$line" | grep '=')" ]; then
            strlen=$(expr length "$line")                       # length of line
            eqsignpos=$(expr index "$line" "=")                 # position of equal sign
            namelen=$(( $eqsignpos - 1 ))                       # length of the name
            valuelen=$(( $strlen - $eqsignpos ))                # length of the value
            valuestart=$(( $eqsignpos + 1 ))                    # index of value
            name=$(expr substr "$line" 1 $namelen)              # stripping name
            value=$(expr substr "$line" $valuestart $valuelen)  # stripping value
            eval "${prefix}__${section}__${name}=\"\$value\""   # building variable
        elif [ -z "$line" ]; then
            : # Ignore empty lines.
        else
            DIE "Error in config file \"$file\" at line $i: $line"
        fi
    done < "$file"

} # function config_read_file



CONFIG_GET_VALUE() {

    local prefix="$1"
    local section="$2"
    local name="$3"

    VARNAME="${prefix}__${section}__${name}"
    OLALA=$(set | grep $VARNAME);
    eval "RS=\"\${$VARNAME}\""

} # function config_get_value



CONFIG_SET_VALUE() {

    local prefix="$1"
    local section="$2"
    local name="$3"
    local value="$4"

    eval "${prefix}__${section}__${name}=\"$value\""

} # function config_set_value



CONFIG_GET_NAMES() {

    local prefix="$1"
    local section="$2"


} # function config_get_names



CONFIG_GET_SECTIONS() {

    local prefix="$1"

    local sections

    local vars



} # function config_get_sections



CONFIG_WRITE_FILE() {

    local prefix="$1"
    local file="$2"

    [ -e "$file" ] || $(echo "" 2>/dev/null 1>$file) || DIE "Cannot create duplicate file \"$file\"."
    [ -f "$file" ] || DIE "Duplicate path \"$file\" is not a file."
    [ -w "$file" ] || DIE "Duplicate file \"$file\" is not writable."


} # function config_write_file




ABS_PATH() {

    local path="$1"
    local cwd

    if [ -z $( echo "$path" | egrep '^/' ) ]; then
        cwd=$( pwd ) || DIE "Cannot get name of current directory (?!)."
        if [ -n $( echo "$path" | egrep '/$' ) ]; then
            path="$cwd$path"
        else
            path="$cwd/$path"
        fi
    fi
    RS="$path"

} # function abs_path


REL_TO_ABS(){
    if echo "$1" | egrep -e ";" -e "'" >/dev/null 2>/dev/null; then
        return 1
    fi

    local rv=
    eval local path=$1
    local link_skip_mode="$2"
    local global_flag=
    local resolved_link=

    [ -z "$link_skip_mode" ] && link_skip_mode=0

    local IS_VALID=`echo "$path" | grep "^/"`
    if [ -z "$IS_VALID" ]; then
        path=$(pwd)"/$path"
    fi

    path=$(echo "$path" | sed 's/\/\/*/\//g')

    local last_dir="$(basename "$path")"
    local prev_dir=$(dirname "$path")
    if [ ! -d "$path" ]; then
        if [ ! -d "$prev_dir" ]; then
            REL_TO_ABS "$prev_dir"
            last_dir=$(echo "$last_dir" | sed 's/\/*$//')
	    RS="$RS/$last_dir"
            rv=1
        else
            last_dir=$(echo "$last_dir" | sed 's/\/*$//')
            GET_PATH_TO_DIRECTORY "$prev_dir"
            if [ "$RS" = "/" ]; then
                RS="$RS$last_dir"
            else
                RS="$RS/$last_dir"
            fi
            rv=0
        fi
    else
        GET_PATH_TO_DIRECTORY "$path"        
        rv=$?
    fi

    if [ "$rv" = "0" ] && [ "0" = "$link_skip_mode" ]; then
        while [ 0 ]; do
	    if [ -L "$RS" ]; then
		resolved_link=$(readlink "$RS")
		global_flag=$(echo "$resolved_link" | grep "^/" 2>/dev/null)
		if [ -z "$global_flag" ]; then
		    RS="$(dirname "$RS")/$resolved_link"
		else
		    RS="$resolved_link"
		fi
	    else
		break
	    fi
	done
        prev_dir=$(dirname "$RS")
        last_dir=$(basename "$RS")
        while [ "$prev_dir" != "/" ]; do
    	    if [ -L "$prev_dir" ]; then
		resolved_link=$(readlink "$prev_dir")
		global_flag=$(echo "$resolved_link" | grep "^/" 2>/dev/null)
		if [ -z "$global_flag" ]; then
		    prev_dir="$(dirname "$prev_dir")/$resolved_link"
		else
		    prev_dir="$resolved_link"
		fi
	    fi
            last_dir="$(basename "$prev_dir")/$last_dir"
            prev_dir=$(dirname "$prev_dir")
        done
        RS="$prev_dir$last_dir"
	REL_TO_ABS "$RS" 1
    fi
    return $rv
}



GET_PATH_TO_DIRECTORY() {
    local path="$1"
    local prev_dir=
    local last_dir=
    (cd "$path" >/dev/null 2>/dev/null)
     if [ "$?" = "0" ]; then
         path=$(cd "$path" >/dev/null 2>/dev/null; pwd)
     else
         prev_dir=$(dirname "$path")
         last_dir=$(basename "$path")
         local flag=0;
         while [ "$flag" != "1" ]; do
             (cd "$prev_dir" >/dev/null 2>/dev/null)
             [ "$?" = "0" ] && path="$prev_dir/$last_dir" && flag=1
             last_dir="$(basename "$prev_dir")/$last_dir"
             prev_dir=$(dirname "$prev_dir")
         done  
     fi
     RS="$path";
     if [ "$path" != "/" ]; then
         return 0
     else
         return 1
     fi
}




COMPARE_VERSION(){
	local A=$1
	local B=$2
        local COMPARE_RESULT=0
        local INDEX=1
        local CA="1"
        local CB="2"

        if [ $(echo $A | grep -v "\.") ] && [ $(echo $B | grep -v "\.") ]; then
		if [ "$A" -gt "$B" ] ; then
		        COMPARE_RESULT=1
		elif [ "$B" -gt "$A" ] ; then
		        COMPARE_RESULT=-1
	        fi # if [ "$A" -gt "$B" ] ; then
		return $COMPARE_RESULT
        fi
       


        while [ "$CA" != "" ] && [ "$CB" != "" ] ; do
		CA=$(echo $A | cut -d'.' -f${INDEX})
		CB=$(echo $B | cut -d'.' -f${INDEX})
		if [ "$CA" != "" ] && [ "$CB" = "" ] ; then
	    		COMPARE_RESULT=1
		elif [ "$CA" = "" ] && [ "$CB" != "" ] ; then
			COMPARE_RESULT=-1
		elif [ "$CA" != "" ] && [ "$CB" != "" ] ; then
	    		if [ "$CA" -gt "$CB" ] ; then
				COMPARE_RESULT=1
			elif [ "$CB" -gt "$CA" ] ; then
				COMPARE_RESULT=-1
	    		fi # if [ "$CA" -gt "$CB" ] ; then
	    		if [ $COMPARE_RESULT -ne 0 ] ; then
				break
	        	fi # if [ "$COMPARE_RESULT" -ne "0" ] ; then
		fi # if [ "$CA" != "" ] && [ "$CB" = "" ] ; then
		INDEX=$(($INDEX+1))
	done #while [ "$CA" != "" ] && [ "$CB" != "" ] ; do
        return $COMPARE_RESULT
	
} # COMPARE_VERSION(){


	




PKG_CHECK(){
	local package=$1
	local pack_ver=$2
	local pack_ver_rel=$3
	local pack='';
	local err=$ERR_OK;
	
	local equal=`echo $pack_ver_rel | sed s/[^e]*e[^e]*//g`
	local greater=`echo $pack_ver_rel | sed s/[^g]*g[^g]*//g`
	local less=`echo $pack_ver_rel | sed s/[^l]*l[^l]*//g`

	local seq=1
	local sgt=1
	local slt=1

	if [ "$pack_ver_rel" = ne ] ; then
		pack=`RPM_INFO $package name`
		err=$?
			
		if [ $err -eq ${ERR_RPM_NO_PACKAGE} ]  ; then 
			return ${ERR_OK}; 
		elif [ $err -ne ${ERR_OK} ] ; then
			return $err;
		fi # if [ $err -eq ${ERR_RPM_NO_PACKAGE} ]  ; then
			
		COMPARE_VERSION `RPM_INFO $package version` $pack_ver
			
		if [ $? -ne 0 ] ; then 
			return ${ERR_OK}; 
		fi # if [ $? -ne 0 ] ; then
		
	fi # if [ "$pack_ver_rel" = ne ] ; then

	if [ "$pack_ver_rel" = eq ] || [ "$pack_ver_rel" = ge ] ||[ "$pack_ver_rel" = lt ] ||[ "$pack_ver_rel" = le ] ||[ "$pack_ver_rel" = gt ] ; then 
		pack=`RPM_INFO $package name`; 
		[ $? -eq ${ERR_OK} ] || err=1; 
		if [ $err -eq ${ERR_OK} ] ; then 
			COMPARE_VERSION `RPM_INFO $package version` $pack_ver
			local error=$?

			if test $equal"x" = "x" ; then
				[ $error -eq 0 ] && seq=0 
			fi # if test $equal"x" = "x" ; then
			if test $greater"x" = "x" ; then
				[ $error -eq 1 ] && sgt=0
			fi # if test $greater"x" = "x" ; then
			if [ $less"x" = "x" ] ; then
				[ $error -eq 255 ] && slt=0
			fi # if [ $less"x" = "x" ] ; then
		fi # if [ $err -eq ${ERR_OK} ] ; then
	fi # if [ "$pack_ver_rel" = eq ] || [ "$pack_ver_rel" = ge...
	

	if [ $err -eq ${ERR_OK} ]; then 
		err=1
		case $pack_ver_rel in
			eq ) [ $seq -ne 0 ] || err=0 ;;
			ge ) [ $seq -ne 0 ] || err=0 ; [ $sgt -eq 1 ] || err=0 ;;
			le ) [ $seq -ne 0 ] || err=0 ; [ $slt -eq 1 ] || err=0 ;;
			gt ) [ $seq -eq 1 ] && [ $sgt -eq 0 ] && err=0 ;;
			lt ) [ $seq -eq 1 ] && [ $slt -eq 0 ] && err=0 ;;
		esac # if [ $err -eq ${ERR_OK} ]; then
	fi # if [ $err -eq ${ERR_OK} ]; then

	return $err

} # PKG_CHECK(){





ARC_GET(){
	arch_tool="uname -m"
	if $($arch_tool | egrep 'i.86' > /dev/null) ; then
		IA='IA32';
		PLATFORM=x32;
	elif $($arch_tool | grep ia64 > /dev/null) ; then 
		IA='IPF'
		PLATFORM=x64
	elif $($arch_tool | grep x86_64 > /dev/null) ; then
		IA='EM64T'
		PLATFORM=x32_64
	else
		LOG "Unknown arch found: $(uname -m)"
		return ${ERR_UNKNOWN_ARC}
	fi # if [ arch | egrep 'i?86' > /dev/null ] ; then
	return ${ERR_OK}
} # ARC_GET(){





RPM_CONFIG(){
	
	[ $RPM_CHECK -eq 1 ] || RPM_INIT ; local err=$?	# RPM tool hasn't been checked yet, perform the check
	[ $err -eq ${ERR_OK} ] || return $err

	[ ${RPM_CONFIGURED} -eq -1 ] || return ${RPM_CONFIGURED}

	ARC_GET

	local rpms="4.2.1(x64) 4.1 4.0.2 3.0.5 4.2.2(x64)"
	local rpmi='';

	for rpmi in $rpms ; do
		LOG "Check if RPM supports relocateable packages - $rpmi"
		local ver=`echo $rpmi | sed s/\(.*\)//g`
		local arc=`echo $rpmi | sed s/.*\(//g | sed s/\)//g`
		if [ "$arc" = "$PLATFORM" ] || [ $arc"x" = $ver"x" ] ; then
			PKG_CHECK rpm $ver eq
			if [ $? -eq 0 ] ; then
				LOG "Non-relocatable version of RPM. RPM version: $ver, ARC: $arc"
				PREFIX='';
				RPM_CONFIGURED=${ERR_RPM_NOT_RELOCATABLE}
				return ${ERR_RPM_NOT_RELOCATABLE}
			fi # if [ $? -eq 0 ] ; then
		fi # if [ "$arc" = "$PLATFORM" ] ; then
	done # for rpmi in $rpms ; do
	RPM_CONFIGURED=${ERR_OK};
	return ${ERR_OK}
} # RPM_CONFIG(){




MAKE_TEMP_FILE() {

    [ $# -eq 0 ] || CROAK "$FUNCNAME() does not expect any arguments."
    LOG_ARGS "$@"
    local temp
    temp=$( RUN mktemp -q "/tmp/install.XXXXXXXX" ) || DIE "Can not create temporary file."
    LOG "ret: <$temp>."
    RS="$temp"

} # create_temp_file



MAKE_TEMP_DIR() {

    [ $# -eq 0 ] || CROAK "$FUNCNAME() does not expect any arguments."
    LOG_ARGS "$@"
    local temp
    temp=$( RUN mktemp -q -d "/tmp/install.XXXXXXXX" ) || DIE "Can not create temporary dir."
    LOG "ret: <$temp>."
    RS="$temp"

} # create_temp_dir




READ_DEFAULT_ANSWER(){	
    local param=$1
    local non_verbose=$2
    local retvalue=''
    LOG "silent:read_default_answer(): Trying to find the parameter '$param'"
    CONFIG_GET_VALUE $CONFIG_PREFIX $CONFIG_SECTION $param
    retvalue=$RS
    if [ -z "$retvalue" ]; then
        [ "1" = "$non_verbose" ] || WARN "Parameter \"$param\" was not found"
        RS=''
    else
        RS=$retvalue
    fi
} #read_default_answer(){



SET_DEFAULT_ANSWER(){	
    local question="$1"
    local value="$2"
    LOG "Set default answer for:"
    LOG_ARGS "$@"
    if IS_COMMAND_LINE_OPTION_EXISTS silent; then
        LOG "Failed, silent mode does not support dynamic default answers."
    else
        CONFIG_SET_VALUE $CONFIG_PREFIX $CONFIG_SECTION $question "$value"
    fi
} #read_default_answer(){



SET_CONFIG_FILE(){
    if IS_COMMAND_LINE_OPTION_EXISTS silent; then
        CONFIG_FILENAME=`GET_COMMAND_LINE_OPTION_VALUE silent` || return 1
        ABS_PATH $CONFIG_FILENAME
        CONFIG_FILENAME=$RS
        CONFIG_READ_FILE $CONFIG_PREFIX $CONFIG_FILENAME
        LOG "CONFIG is set to '$CONFIG_FILENAME'"
    else
        LOG "Silent mode was not enabled"
    fi
} # set_config_file()



KEEP_ANSWERS(){
    if IS_COMMAND_LINE_OPTION_EXISTS duplicate; then
        local dup_filename=`GET_COMMAND_LINE_OPTION_VALUE duplicate`
        ABS_PATH $dup_filename
        dup_filename=$RS
        CONFIG_WRITE_FILE $CONFIG_PREFIX $dup_filename
        LOG "Duplicate was performed into '$dup_filename'"
    else
        LOG "Duplicate mode was not enabled"
    fi
}



JOIN() {

    [ $# -ge 1 ] || croak "$FUNCNAME() expects at least 1 argument."

    local joiner="$1"
    shift 1

    JOIN3 "" "" "$joiner" "$@"

} # function join



JOIN3() {
    [ $# -ge 3 ] || croak "$FUNCNAME() expects at least 3 arguments."

    local prefix="$1"
    local suffix="$2"
    local joiner="$3"
    shift 3

    local result=
    if [ $# -gt 0 ]; then
        count=0;
        for string in "$@"; do
            count=$(( $count + 1 ))
        done 
        i=0
        for string in "$@"; do
            if [ $i -eq 0 ]; then
                result="${prefix}${string}${suffix}";
            else
                result="${result}${joiner}${prefix}${string}${suffix}";
            fi;
            i=$(( $i + 1 ));
        done
    fi;

    RS="$result"
} # function join3





DIE() {
    local opts=""
    local log="log"
    local prefix="ERROR: "
    while [ -n "$(echo "$1" | egrep "^\-[a-zA-Z]$" )" ]; do
        case "$1" in
            -L ) log="";;
            -P ) prefix="";;
            *  ) opts="$opts $1";;
        esac
        shift 1
    done
    [ -n "$log" ] && LOG "warn:" "$@" "(end)"
    local message
    for message in "$@"; do
        echo $opts "$prefix$message" 1>&2
    done
    BYE 1
} # function die



BYE() {

    local code="$1"

    [ -z "$code" ] && code="0"
    LOG "bye ($code)."

    exit "$code"

} # function bye

_croak_() {

    local level=$(( $1 + 2 ))
    shift 1

    DIE "Internal error: $@ Please report."

} # function _croak_

croak0() {

    _croak_ 0 "$@"

} # function croak0



CROAK() {

    _croak_ 1 "$@"

} # function croak



INIT_LOG() {

    if [ -z "$LOG_F" ]; then
	local param=$1
	if [ -z "$param" ]; then
	    WARN -L "LOG file was not specified. Logging will be disabled."
	else
	    LOG_F=$param
	fi
    fi
    
    [ -e "$LOG_F" ] || RUN :>"$LOG_F" 
    echo "-+ Logging in shell wrapper is started with LOG=$LOG_F +-" >> "$LOG_F"
    if [ $? -ne 0 ]; then
	WARN -L "Can not write log file \"$LOG_F\". Logging will be disabled."
	unset LOG_F
    fi

} # function init_log



LOG() {

    if [ -n "$LOG_F" ]; then
        local time_stamp="$( date +'%a %b %d %T' )"
        local line
        for line in "$@"; do
            { echo "$time_stamp: $line" >> "$LOG_F"; } 2> /dev/null
            if [ $? -ne 0 ]; then
                WARN -L "Can not write log file \"$LOG_F\"."
                unset LOG_F  # Unset LOG variable not to log any messages any more.
                break
            fi
        done
    fi

} # function log



LOG_ARGS() {

    JOIN3 "<" ">" ", " "$@"
    if [ -n "$RS" ]; then
        LOG "$RS."
    fi

} # function log_args



LOG_VARS() {

    local name str
    local vars=" "
    for name in "$@"; do
        vars="${vars} $name";
    done
    JOIN ", " "${vars}"
    LOG "vars: $RS."

} # function log_vars



LOG_FILE() {

    local file="$1"
    local line

    LOG \
        "file <$file>:" \
        "+-------------------------------------------------------------------------------"
    if [ -f "$file" ]; then
        while read line; do
            LOG "| $line"
        done < "$file"
    else
        LOG "file not found"
    fi
    LOG "+-------------------------------------------------------------------------------"

} # function log_file



WARN() {
    local opts=""
    local log="log"
    local prefix="WARNING: "
    while [ -n "$(echo "$1" | egrep '^\-[a-zA-Z]$')" ]; do
        case "$1" in
            -L ) log="";;
            -P ) prefix="";;
            *  ) opts="$opts $1";;
        esac
        shift 1
    done
    [ -n "$log" ] && LOG_ARGS "$@"
    local message
    for message in "$@"; do
        echo $opts "$prefix$message" 1>&2
    done
} # function warn






RPM_INIT(){
	[ ${RPM_CHECK} -eq 0 ] || return ${ERR_OK}
	rpm -q rpm >/dev/null 2>&1

	if [ $? -ne 0 ] ; then
		LOG "Cannot get shared lock on RPM Database"
		return ${ERR_RPM_LOCK}
	fi

	RPM_CHECK=1
	
	return ${ERR_OK}
} # RPM_INIT(){   





CHECK_GROUP_EXISTS(){
    local group=$1
    `groupmod $group >/dev/null 2>/dev/null`
    if [ $? -ne 0 ] ; then
        return ${ERR_GROUP_NOT_EXISTS}
    fi # if ! cat /etc/group | egrep "^${gropup}:" >/dev/null 2>/dev/null ; then
    return ${ERR_OK}
} #CHECK_GROUP_EXISTS()



CHECK_NIS_GROUP_EXISTS(){
    local group=$1
    if ypcat group 2>/dev/null | cut -d : -f1 | grep "^$group$" >/dev/null 2>/dev/null ; then
        return ${ERR_OK}
    elif getent group 2>/dev/null | cut -d : -f1 | grep "^$group$" >/dev/null 2>/dev/null ; then
        return ${ERR_OK}
    else
        return ${ERR_GROUP_NOT_EXISTS}
    fi
    
} #CHECK_NIS_GROUP_EXISTS()



ADD_GROUP(){
    local group=$1
    local force_update=$2
    local err=0


    [ ! -z $force_update ] || force_update=0
    [ "$force_update" = "0" ] || force_update=1

    CHECK_GROUP_EXISTS $group
    
    if [ $? -eq ${ERR_GROUP_NOT_EXISTS} ] ; then 
        groupadd $group >/dev/null 2>/dev/null
        if [ $? -ne 0 ] ; then 
            LOG "Unable to create new group \"$group\"." "Failed"
            return ${ERR_USER} 
        else
            LOG "The group \"$group\" was created."
        fi # if [ $? -ne 0 ] ; then
    else
        return ${ERR_GROUP_EXISTS}
    fi # if [ $? -eq 0 ] ; then
    return ${ERR_OK}

} # ADD_GROUP(){



DEL_GROUP(){
    
    local group=$1
    local err=0


    CHECK_GROUP_EXISTS $group

    if [ $? -eq ${ERR_OK} ] ; then 
        groupdel $group
        err=$?
    else
        LOG "Group: '${group}' does not exists"
        return ${ERR_GROUP_NOT_EXISTS}
    fi # if [ $? -ne 0 ] ; then

    if [ $err -ne 0 ] ; then
        LOG "Can't remove group: '${group}'"
        return ${ERR_GROUP}
    else
        LOG "Group: '${group}' successfuly removed"
    fi # if [ $? -ne 0 ] ; then

    return ${ERR_OK}
} # DEL_GROUP{                                        




IS_ONE_OF() {

    [ $# -ge 1 ] || CROAK "$FUNCNAME() expects at least one argument."

    local item="$1"
    shift 1

    local iter
    for iter in "$@"; do
        if [ "$item" = "$iter" ]; then
            return 0
        fi
    done
    return 1

} # is_one_of





SPLIT() {

    local delimiter="$1"
    local string="$2"
    local result=""

    [ $# -eq 2 ] || CROAK "$FUNCNAME() expects 2 arguments."
    [ "${#delimiter}" -eq 1 ] || CROAK "$FUNCNAME(): The 1st argument must be a single char."

    strlen=${#string}
    str_wo_del=$(echo "$string" | tr -d "$delimiter")
    str_wo_del_len=${#str_wo_del}
    elemcount=$(( $strlen - $str_wo_del_len + 1 ));
    i=1;
    while [ $i -le $elemcount ]; do
        next=$(echo "$string" | cut -d "$delimiter" -f $i);
        [ -n $next ] && result="$result $next"
        i=$(( $i + 1 ));
    done;

    RA=$result;

} # function split






INTEL_SDP_PRODUCTS_DB=intel_sdp_products.db # TBD...
INTEL_SDP_PRODUCTS_DB_LOCAL=''
NONRPM_DB_MODE=''
NONRPM_DB_PREFIX="$HOME/intel"

NONRPM_SET_DB_MODE(){
    [ -z "$NONRPM_DB_MODE" ] || return 0
    LOG "NONRPM_SET_DB_MODE"

    INTEL_SDP_PRODUCTS_DB="$NONRPM_DB_PREFIX/$INTEL_SDP_PRODUCTS_DB"
    LOG "INTEL_SDP_PRODUCTS_DB set to $INTEL_SDP_PRODUCTS_DB"

    if IS_COMMAND_LINE_OPTION_EXISTS use-new-db; then
	NONRPM_DB_MODE="both"
    elif IS_COMMAND_LINE_OPTION_EXISTS ignore-old-db; then
	NONRPM_DB_MODE="new"
    else
	NONRPM_DB_MODE="old"
    fi
    LOG "NONRPM_DB_MODE set to $NONRPM_DB_MODE"
    
    if IS_COMMAND_LINE_OPTION_EXISTS nonrpm; then 
	if [ -e "$NONRPM_DB_PREFIX" ]; then
	    if [ ! -d "$NONRPM_DB_PREFIX" ]; then
		LOG "$NONRPM_DB_PREFIX is exist and this is not a directory"
		DIE "$NONRPM_DB_PREFIX is exist and this is not a directory"
	    fi
	else
	    mkdir -p "$NONRPM_DB_PREFIX" >/dev/null 2>/dev/null
	    if [ "$?" != "0" ]; then
		LOG "Unable to create a directory $NONRPM_DB_PREFIX"
		DIE "Unable to create a directory $NONRPM_DB_PREFIX"
	    fi
	fi  
    fi
    
    if [ "$NONRPM_DB_MODE" != "old" ]; then
	LOG "Using INTEL_SDP_PRODUCTS_DB_LOCAL="
	if [ "x$INSTALL_HOST_ID" != "x" ]; then
	    LOG "via INSTALL_HOST_ID var"
	    INTEL_SDP_PRODUCTS_DB_LOCAL="$NONRPM_DB_PREFIX/intel_sdp_products_$INSTALL_HOST_ID.db"
	else
	    LOG "via <hostname>"
	    RS=$(hostname)
	    if [ "$?" != "0" ]; then
		WARN "Unable to define host name, 'only-old-db' mode will be used for Non-rpm functionality."
		INTEL_SDP_PRODUCTS_DB_LOCAL=''
		NONRPM_DB_MODE="old"
	    else
		INTEL_SDP_PRODUCTS_DB_LOCAL="$NONRPM_DB_PREFIX/intel_sdp_products_$RS.db"
	    fi
	fi
	LOG "INTEL_SDP_PRODUCTS_DB_LOCAL set to $INTEL_SDP_PRODUCTS_DB_LOCAL"
	if IS_COMMAND_LINE_OPTION_EXISTS nonrpm; then
	    [ -e "$INTEL_SDP_PRODUCTS_DB_LOCAL" ] || RUN echo -n "" 2>/dev/null 1>$INTEL_SDP_PRODUCTS_DB_LOCAL
	fi
    fi
    
    if IS_COMMAND_LINE_OPTION_EXISTS nonrpm; then
	if [ "$NONRPM_DB_MODE" = "old" ] || [ "$NONRPM_DB_MODE" = "both" ]; then 
	    [ -e "$INTEL_SDP_PRODUCTS_DB" ] || RUN echo -n "" 2>/dev/null 1>$INTEL_SDP_PRODUCTS_DB
	fi
    fi
    
    return 0
}



NONRPM_GET_BUFFER(){
    
    LOG "NONRPM_GET_BUFFER"
    NONRPM_SET_DB_MODE
    
    local result=''
    local rst=1
    case $NONRPM_DB_MODE in
    new)
	LOG "case new"
	result=$(cat "$INTEL_SDP_PRODUCTS_DB_LOCAL" 2>/dev/null)
	rst=$?
	;;
    both)
	LOG "case both"
	result=$(cat "$INTEL_SDP_PRODUCTS_DB" "$INTEL_SDP_PRODUCTS_DB_LOCAL" 2>/dev/null | sort | uniq)
	rst=$?
	;;
    *)
	LOG "case any"
	result=$(cat "$INTEL_SDP_PRODUCTS_DB" 2>/dev/null)
	rst=$?
	;;
    esac

    if IS_COMMAND_LINE_OPTION_EXISTS nonrpm; then
	[ "$rst" = "0" ] || return 1
    fi
    
    LOG "result:"
    LOG "$result"

    RS=$result
    return 0
}



NONRPM_DB_ENTRY_CHECK_SYNTAX() {
    local entry="$1"
    local regexp='<:[^:]*:intel-[a-z_0-9-]+-[0-9]+(\.[0-9]+)+([abpet]u?)?-[0-9]+\.?[a-z_0-9]+\.rpm:[^:]*:[^:]*:>'
    return $(echo "$entry" | grep -E -x "$regexp" > /dev/null) \
        || FATAL_EXIT "Unexpected error."
} # NONRPM_DB_ENTRY_CHECK_SYNTAX



NONRPM_DB_ENTRY_GET_FIELD() {
    local entry="$1"
    local field="$2"
    RS=''
	if ! NONRPM_DB_ENTRY_CHECK_SYNTAX "$entry"; then
        return 1
    fi
    if [ "$field" -lt 2 ] || [ "$field" -gt 5 ]; then
        return 2
    fi
    local result=$(echo "$entry" | cut -d':' -f"$field") \
        || FATAL_EXIT "Unexpected error"
    RS=$result
    return 0
} # NONRPM_DB_ENTRY_GET_FIELD


NONRPM_DB_ENTRY_GET_RPMNAME() {
    NONRPM_DB_ENTRY_GET_FIELD "$1" 2
    return $?
} # NONRPM_DB_ENTRY_GET_RPMNAME

NONRPM_DB_ENTRY_GET_RPMFILE() {
    NONRPM_DB_ENTRY_GET_FIELD "$1" 3
    return $?
} # NONRPM_DB_ENTRY_GET_RPMFILE

NONRPM_DB_ENTRY_GET_INSTALLDIR() {
    NONRPM_DB_ENTRY_GET_FIELD "$1" 4
    return $?
} # NONRPM_DB_ENTRY_GET_INSTALLDIR

NONRPM_DB_ENTRY_GET_LOGFILE() {
    NONRPM_DB_ENTRY_GET_FIELD "$1" 5
    return $?
} # NONRPM_DB_ENTRY_GET_LOGFILE



NONRPM_DB_ENTRY_ADD() {

    LOG "NONRPM_DB_ENTRY_ADD"
    LOG_ARGS $@
    local entry="$1"

    NONRPM_SET_DB_MODE

    if ! NONRPM_DB_ENTRY_CHECK_SYNTAX "$entry"; then
        return 1
    fi

    local db_content=
    if [ "$NONRPM_DB_MODE" = "old" ] || [ "$NONRPM_DB_MODE" = "both" ]; then
	db_content=$(cat "$INTEL_SDP_PRODUCTS_DB" 2>/dev/null)
	echo "$entry" > "$INTEL_SDP_PRODUCTS_DB"
	[ -z "$db_content" ] || echo "$db_content" >> "$INTEL_SDP_PRODUCTS_DB"
	if [ $? -ne 0 ]; then
	    return 2
	fi
    fi

    if [ "$NONRPM_DB_MODE" = "new" ] || [ "$NONRPM_DB_MODE" = "both" ]; then
	db_content=$(cat "$INTEL_SDP_PRODUCTS_DB_LOCAL" 2>/dev/null)
	echo "$entry" > "$INTEL_SDP_PRODUCTS_DB_LOCAL"
	[ -z "$db_content" ] || echo "$db_content" >> "$INTEL_SDP_PRODUCTS_DB_LOCAL"
	if [ $? -ne 0 ]; then
	    return 2
	fi
    fi
    
    return 0
    
} # NONRPM_DB_ENTRY_ADD



NONRPM_DB_ENTRY_REMOVE() {

    LOG "NONRPM_DB_ENTRY_REMOVE"
    LOG_ARGS $@
    local entry="$1"

    NONRPM_SET_DB_MODE

    if ! NONRPM_DB_ENTRY_CHECK_SYNTAX "$entry"; then
        return 1
    fi

    local DB_CONTENTS=''

    if [ "$NONRPM_DB_MODE" = "old" ] || [ "$NONRPM_DB_MODE" = "both" ]; then
	cp -p "$INTEL_SDP_PRODUCTS_DB" "$INTEL_SDP_PRODUCTS_DB~" \
	    || DIE "Unable to create backup copy of \"$INTEL_SDP_PRODUCTS_DB\" file."
	grep -F -v -x "$entry" "$INTEL_SDP_PRODUCTS_DB~" > "$INTEL_SDP_PRODUCTS_DB"
	local rc=$?
	[ $rc -le 1 ] || DIE "Unable to overwrite \"$INTEL_SDP_PRODUCTS_DB\" file."
	chmod --reference="$INTEL_SDP_PRODUCTS_DB~" "$INTEL_SDP_PRODUCTS_DB" \
	    || DIE "Unable to change permissions on \"$INTEL_SDP_PRODUCTS_DB\" file."
	rm -f "$INTEL_SDP_PRODUCTS_DB~" >/dev/null 2>/dev/null
                          
        DB_CONTENTS=$(cat "$INTEL_SDP_PRODUCTS_DB")
        [ -z "$DB_CONTENTS" ] && rm -rf "$INTEL_SDP_PRODUCTS_DB" >/dev/null 2>/dev/null
    fi
    
    if [ "$NONRPM_DB_MODE" = "new" ] || [ "$NONRPM_DB_MODE" = "both" ]; then
	cp -p "$INTEL_SDP_PRODUCTS_DB_LOCAL" "$INTEL_SDP_PRODUCTS_DB_LOCAL~" \
	    || DIE "Unable to create backup copy of \"$INTEL_SDP_PRODUCTS_DB_LOCAL\" file."
	grep -F -v -x "$entry" "$INTEL_SDP_PRODUCTS_DB_LOCAL~" > "$INTEL_SDP_PRODUCTS_DB_LOCAL"
	local rc=$?
	[ $rc -le 1 ] || DIE "Unable to overwrite \"$INTEL_SDP_PRODUCTS_DB_LOCAL\" file."
	chmod --reference="$INTEL_SDP_PRODUCTS_DB_LOCAL~" "$INTEL_SDP_PRODUCTS_DB_LOCAL" \
	    || DIE "Unable to change permissions on \"$INTEL_SDP_PRODUCTS_DB_LOCAL\" file."
	rm -f "$INTEL_SDP_PRODUCTS_DB_LOCAL~" >/dev/null 2>/dev/null

        DB_CONTENTS=$(cat "$INTEL_SDP_PRODUCTS_DB_LOCAL")
        [ -z "$DB_CONTENTS" ] && rm -rf "$INTEL_SDP_PRODUCTS_DB_LOCAL" >/dev/null 2>/dev/null
    fi
    
    return 0

} # NONRPM_DB_ENTRY_REMOVE


NONRPM_DB_IS_PACKAGE_INSTALLED() {

    LOG "NONRPM_DB_FIND_FILE_OWNER"
    LOG_ARGS $@
    local package="$1"
    local rc

    NONRPM_GET_BUFFER
    if [ "$?" != "0" ]; then
	DIE "Unable to obtain non-rpm DB content"
    fi

    echo $RS | grep ":$package" >/dev/null 2>/dev/null
    rc=$?
    if [ $rc -ge 2 ]; then
        DIE "Unexpected error."
	RS=''
    fi

    RS=$rc
    return $rc
} # NONRPM_DB_IS_PACKAGE_INSTALLED



NONRPM_DB_FIND_FILE_OWNER() {

    LOG "NONRPM_DB_FIND_FILE_OWNER"
    LOG_ARGS $@
    local file="$1"
    local entry
    local log_file
    local owner

    NONRPM_GET_BUFFER
    if [ "$?" != "0" ]; then
	DIE "Unable to obtain non-rpm DB content"
    fi

    local buffer="$RS"
    for entry in $buffer; do
	NONRPM_DB_ENTRY_GET_LOGFILE "$entry"
        log_file=$RS
        if [ $? -eq 0 ] && [ -f "$log_file" ]; then
            owner=$(grep -F -x -l "$file" "$log_file")
            if [ $? -ge 2 ]; then
                DIE "Unexpected error."
            fi
            if [ -n "$owner" ]; then
                RS=$entry
                return 0
            fi
        fi
    done
    
    RS=''
    return 1

} # NONRPM_DB_FIND_FILE_OWNER


NONRPM_DB_ENTRY_FIND_BY_RPMNAME() {

    LOG "NONRPM_DB_ENTRY_FIND_BY_RPMNAME"
    LOG_ARGS $@
    local rpmname=$(basename "$1")
    local entry
    local r_entries=

    NONRPM_GET_BUFFER
    if [ "$?" != "0" ]; then
	DIE "Unable to obtain non-rpm DB content"
    fi

    local buffer="$RS"
    for entry in $buffer; do
	NONRPM_DB_ENTRY_GET_RPMNAME "$entry"
        if [ "$rpmname" = "$RS" ]; then
	    LOG "Entry $entry found"
            RS="$entry"
	    return 0
        fi
    done
    RS=''
    return 1

} # NONRPM_DB_ENTRY_FIND_BY_RPMNAME



NONRPM_DB_ENTRY_FIND_BY_RPMFILE() {

    LOG "NONRPM_DB_ENTRY_FIND_BY_RPMFILE"
    LOG_ARGS $@
    local rpmfile=$(basename "$1")
    local entry
    local r_entries=

    NONRPM_GET_BUFFER
    if [ "$?" != "0" ]; then
	DIE "Unable to obtain non-rpm DB content"
    fi

    local buffer="$RS"
    for entry in $buffer; do
	NONRPM_DB_ENTRY_GET_RPMFILE "$entry"
        if [ "$rpmfile" = "$RS" ]; then
	    LOG "Entry $entry found"
            r_entries="$r_entries $entry"
        fi
    done
    RS=$r_entries
    return 0

} # NONRPM_DB_ENTRY_FIND_BY_RPMFILE



NONRPM_DB_FIND_BY_INSTALLDIR() {

    LOG "NONRPM_DB_FIND_BY_INSTALLDIR"
    LOG_ARGS $@
    local installdir="$1"
    local entry

    NONRPM_GET_BUFFER
    if [ "$?" != "0" ]; then
	DIE "Unable to obtain non-rpm DB content"
    fi

    local buffer="$RS"
    for entry in $buffer; do
	NONRPM_DB_ENTRY_GET_INSTALLDIR "$entry"
        if [ "$installdir" = "$RS" ]; then
	    LOG "Entry $entry found"
            RS=$entry
            return 0
        fi
    done
    
    RS=''
    return 1

} # NONRPM_DB_FIND_BY_INSTALLDIR



NONRPM_DB_CHECK_SHARED_FILES() {
    local install_dir="$1"
    local log_file="$2"

    local entry
    local line
    local shared=""

    NONRPM_GET_BUFFER
    if [ "$?" != "0" ]; then
	DIE "Unable to obtain non-rpm DB content"
    fi

    local buffer="$RS"
    for entry in $buffer; do
	NONRPM_DB_ENTRY_GET_INSTALLDIR "$entry"
	if [ "$install_dir" = "$RS" ]; then
	    NONRPM_DB_ENTRY_GET_LOGFILE "$entry"
	    [ "x$RS" = "x$log_file" ] || shared="$RS $shared"
	fi
    done
    
    local rt
    tac "$log_file" | \
    while read line; do
	rt=1
	if [ "x$shared" != "x" ]; then
	    for i in "$shared"; do
		$(cat $i | grep $line >/dev/null 2>/dev/null)
		rt=$?
		[ $rt -eq 0 ] && break
	    done
	fi
	if [ $rt -eq 0 ]; then
	    LOG "Shared violation $line"
	    continue
	fi 
        if [ -h "$line" ] || [ -f "$line" ]; then
            rm -f "$line"
        elif [ -d "$line" ]; then
            rmdir --ignore-fail-on-non-empty "$line"
        else
            echo "Warning: installed \"$line\" file not found"
        fi	
    done
}



NONRPM_DB_GET_RPMBASED_FIELD(){
	local entry=""$1
	local field=""$2

	LOG "NONRPM_DB_GET_RPMBASED_FIELD:"
	LOG_ARGS $@
	NONRPM_DB_ENTRY_GET_FIELD $entry "2"
	local rpm_name=$RS
	NONRPM_DB_ENTRY_GET_INSTALLDIR "$entry"
	local dir=$RS
	
	LOG "Try to extract $dir/.scripts/$field.$rpm_name"
	if [ -f "$dir/.scripts/$field.$rpm_name" ]; then
		LOG_FILE "$dir/.scripts/$field.$rpm_name"
		RS=$(cat "$dir/.scripts/$field.$rpm_name")
		return 0 
	else
		RS=''
		LOG "$field does not exist in script dir"
	fi
	return 1
}




SAVE_COMMAND_LINE(){
    CMD_STR=$@
    export CMD_STR   
} #SAVE_COMMAND_LINE



IS_COMMAND_LINE_OPTION_EXISTS(){
    local cmd=$1
    if echo $CMD_STR | egrep -i "\-\-$cmd" > /dev/null 2>&1 ; then
        return ${ERR_OK}
    fi

    return 1
} # is_command_line_option_exists()



GET_COMMAND_LINE_OPTION_VALUE(){
    local cmd=$1
    local err=0;

    IS_COMMAND_LINE_OPTION_EXISTS $cmd
    err=$?
    [ $err -eq ${ERR_OK} ] || return 1

    RS=$(echo $CMD_STR | sed s/.*--$cmd[[:blank:]]*//g | sed 's/[[:blank:]]*[[:blank:]]\-\-.*$//g')
    [ -n "$RS" ] || return 1

    echo $RS
} # get_command_line_option_value() {




RPM_INFO(){
	local rpm_name=$1
	local rpm_tag=$2
	
	[ $RPM_CHECK -eq 1 ] || RPM_INIT ; local err=$?
	[ $err -eq ${ERR_OK} ] || return $err
	
	local opt="-q"
	if [ -f "$rpm_name" ]; then
		LOG "Using file query for package - '$rpm_name'"
		opt="-qp"
	fi #if[ -x $rpm_name ]; then
	
	local rpm_out_count=`rpm $opt $rpm_name 2>&1 | wc -l`
	if [ $rpm_out_count -eq 1 ] ; then 
		local info=`rpm $opt $rpm_name --qf %{$rpm_tag} 2>&1`
		if [ -z $( echo $info | grep installed >/dev/null 2>/dev/null ) ]; then
			echo $info
			LOG "Package search: '$rpm_name' => '$rpm_tag' => '$info' "
			return $ERR_OK;
		fi #if ! echo $info | grep installed >/dev/null 2>&1 ; then
	else
		local out=
                local i=1
			local info=`rpm $opt $rpm_name --qf %{$rpm_tag}"\n" 2>&1 | sed $i'!d'`
			out="$out$info"
                echo $info
		LOG "Multiple package search: '$rpm_name' => '$rpm_tag' => '$out' "
		return ${ERR_OK}
	fi

	LOG "Package '$rpm_name' not found"
	
	return ${ERR_RPM_NO_PACKAGE}
} # RPM_INFO(){





RUN() {

    [ $# -ge 1 ] || CROAK "$FUNCNAME() expects at least one argument."

    local rc
    LOG_ARGS "$@"
    "$@"
    rc=$?
    LOG "ret: $rc."
    return $rc

} # function run





GET_USER_INTERACTIVE_ANSWER() {
    local question_id="$1"
    local question="$2"
    local USE_READLINE="$3"
    local l_answer=

    LOG "interact:get_user_interactive_answer(): getting answer on the question with id '$question_id'"
    if IS_COMMAND_LINE_OPTION_EXISTS silent ; then
        READ_DEFAULT_ANSWER $question_id
        l_answer=$RS
    else
        if [ "NO" = "$USE_READLINE" ]; then
            read -e -p "$question" l_answer
        else
            read -p "$question" l_answer
        fi

        if [ -z "${l_answer}" ] ; then # user has pressed <Enter>
            LOG "interact:get_user_interactive_answer(): user entered empty answer"
            LOG "interact:get_user_interactive_answer(): using default answer"
            READ_DEFAULT_ANSWER $question_id
            l_answer=$RS
        else
            LOG "interact:get_user_interactive_answer(): the answer is '$l_answer'"
        fi
    fi

    RS=$l_answer
} # get_user_interactive_answer


READ_YES_NO_ANSWER ()
{
    local QUESTION="$1"
    local question_id="$2"
    local YES_ANSWER="y yes yea yeah yep ok"    # these answers are recognized as 'Yes'
    local NO_ANSWER="n no not nop nope"         # these answers are recognized as 'No'
    local DEFAULT_ANSWER=

    if ! IS_COMMAND_LINE_OPTION_EXISTS silent; then
        READ_DEFAULT_ANSWER $question_id
        DEFAULT_ANSWER=$RS
    fi

    while [ true ]; do
        IS_COMMAND_LINE_OPTION_EXISTS silent || DISPLAY_QUESTION "" "$QUESTION" "Yes/No" "$DEFAULT_ANSWER"
        GET_USER_INTERACTIVE_ANSWER $question_id
        yesno="$(echo $RS | tr -s A-Z a-z)"
        if FIND_STRING $yesno ";" "$YES_ANSWER";then
            LOG "interact: READ_YES_NO_ANSWER (): the answer is Yes"
            RS="yes"
            return 0
        else
            if FIND_STRING $yesno ";" "$NO_ANSWER"; then
                LOG "interact: READ_YES_NO_ANSWER (): the answer is No"
                RS="no"
                return 1
            fi
            if IS_COMMAND_LINE_OPTION_EXISTS silent; then
                LOG "interact: READ_YES_NO_ANSWER (): couldn't recognize the answer: config file parameter '$question_id' has wrong value '$answer'"
                return 2
            fi
        fi
    done
}



WAIT_ENTER_KEY ()
{
    IS_COMMAND_LINE_OPTION_EXISTS silent || read wontuse
}



SAY() {
    local opts=""
    local log="log"
    while [ -n "$(echo "$1" | egrep "^\-[a-zA-Z]$")" ]; do
        case "$1" in
            -L ) log="" ;;
            *  ) opts="$opts $1" ;;
        esac
        shift 1
    done
    [ -n "$log" ] && LOG_ARGS "$@"
    local message
    for message in "$@"; do
        echo $opts "$message"
    done
} # function say



TELL() {
    LOG_ARGS "$@"
    set_tell_fmt
    if [ -n "$_TELL_FMT_" ]; then
        echo "$*" | "$_TELL_FMT_" -s -w "$TELL_WIDTH"
    else
        echo "$*"
    fi
} # function tell

set_tell_fmt() {
    [ "set" = "$_SET_FMT_" ] && return 0

    _FMT=`which fmt 2>/dev/null`;
    if [ -n "$_FMT" ]; then
        _TELL_FMT_="fmt"
    else 
        _TELL_FMT_=
        WARN "Unable to find command \"fmt\". Some messages may be too long." 
    fi

    _SET_FMT_="set"
}



ASK() {

    [ $# -ge 2 && $# -le 4 ] || CROAK "$FUNCNAME() expects from 2 to 4 arguments."
    LOG_ARGS "$@"

    local text="$1"
    local prompt="$2"      # Question itself.
    local options="$3"     # List of possible answers, delimited with '/'.
    local default="$4"     # Default answer to be used if user pressed Enter immediately.
    local answer

    SPLIT "/" "$options"
    local opt_list
    opt_list="$RA"

    if [ -n "$options" ]; then
        prompt="$prompt ($options)"
    fi
    if [ -n "$default" ]]; then
        prompt="$prompt [$default]"
    fi

    if [ -n "$text" ]; then
        SAY -L -e "$text"
    fi

    while [ true ]; do
        read -e -p "$prompt: " answer
        LOG "read: <$answer>."
        if [ -z "$answer" ]; then
            answer="$default"
        fi
        if [ -z "$options" ] || IS_ONE_OF "$answer" "$opt_list"; then
            SAY -L ""
            RS="$answer"
            LOG "ret: <$answer>"
            return
        fi
        MAKE_LIST "$opt_list"
        SAY "Please enter $RS."
    done

} # function ask



DISPLAY_QUESTION(){
    local intro="$1"
    local q="$2"
    local da="$3"
    local rda="$4"

    IS_COMMAND_LINE_OPTION_EXISTS silent && return ${ERR_OK}
    LOG_ARGS $@

    [ -n "$intro" ] && echo $intro
    echo -n "$q"
    [ -n "$da" ] && echo -n " ( $da )"
    [ -n "$rda" ] && echo -n " [ $rda ]"
    echo -n ": "
}



FIND_STRING()
{
    local s="$1"
    local a=
    while [ true ]; do
        [ ";" = "$1" ] && break
        shift
    done

    LOG "Checking '$s' against this list: $@"
    for a in $@; do
        if [ "$s" = "$a" ];then
            LOG "Found"
            return ${ERR_OK}
        fi
    done
    LOG "Haven't found '$s'"
    return 1
}




TOUCH_SPACE(){
	
	local dir_to_check=$1
	local dir_end_path='hags7823782318#@123kjhknmnzxmnz'
	local err=

        [ -L "$dir_to_check" ] && dir_to_check=$(readlink "$dir_to_check")

	if [ -e "$dir_to_check" ] ; then
	    if [ -d "$dir_to_check" ]; then
		if [ -w "$dir_to_check" ] ; then
			RUN mkdir "$dir_to_check/$dir_end_path" >/dev/null 2>/dev/null
			err=$?
			if [ $err -eq ${ERR_OK} ] ; then
				RUN rmdir "$dir_to_check/$dir_end_path" >/dev/null 2>/dev/null
			fi # if [ $err -eq ${ERR_OK} ] ; then
		else
			err=1
		fi # if [ -w "$dir_to_check" ] ; then
	    else
		err=1
	    fi
	else
		TOUCH_SPACE "`dirname "$dir_to_check"`" "$dir_end_path"
		err=$?
	fi # if [ -d "$dir_to_check" ] ; then

	LOG "Access for write $dir_to_check/$dir_end_path, exit code: $err"
	
	return $err
} #TOUCH_SPACE(){



CHECK_FREE_SPACE(){
    local path="$1"
    local needed_space="$2"	# Disc space in MegaBytes, should be integer
    
    LOG "CHECK_FREE_SPACE:"
    LOG_ARGS "$@"
    
    local base=$path

    while [ ! -d "$base" ] ; do
        base=$(dirname "$base")
    done
        
    local available=0
    available=$(df -Pm "$base" 2>/dev/null | tail -n1 | tr -s [:space:] | cut -d' ' -f4)
    RS=$?

    [ "$RS" = "0" ] || return 1
    
    LOG "Available disc space on this mount is $available"
    
    if [ "$needed_space" -le "$available" ]; then
	return 0
    else 
	LOG "Trere is no enough space on this mount"
        return 1
    fi
}



CHECK_DESTINATION(){
	local path="$1"
	local needed_space="$2"
    local verbose=$3
	local lrs=1
	local owner=
	local summary=

	LOG "CHECK_DESTINATION"
	LOG_ARGS "$@"

	if echo "$path" | grep " " >/dev/null 2>/dev/null ; then
		WARN "Incorrect directory name. Directory name can't contain spaces."
		RS="$path"
		return 1
	fi
	if echo "$path" | grep '\\' >/dev/null 2>/dev/null ; then
		WARN "Incorrect directory name. Directory name can't contain '\\' symbols."
		RS="$path"
		return 1
	fi
	if echo "$path" | grep "	" >/dev/null 2>/dev/null ; then
		WARN "Incorrect directory name. Directory name can't contain tabs."
		RS="$path"
		return 1
	fi
	if echo "$path" | grep -e"\@" -e"&" -e"\`" -e"'" -e"\[" -e"\]" -e"'" -e":" -e"\"" >/dev/null 2>/dev/null ; then
		WARN "Incorrect directory name. Directory name can't contain '@', '&', '\`', ''', '[', ']', ':' and '\"' symbols."
		RS="$path"
		return 1
	fi

	REL_TO_ABS "$path"
	if [ $? -ne 0 ]; then
	    WARN "Incorrect directory name."
	    RS="$path"
	    return 1
	fi
	path="$RS"

	local check=$(echo "$path" | grep "^/")
	if [ -z "$check" ]; then
		WARN "Incorrect directory name."
		return 1
	fi

    if [ -f "$path" ]; then
        WARN "Incorrect directory name. '$path' exists but it is not a directory."
	    RS="$path"
        return 1
    fi

	TOUCH_SPACE "$path"
	lrs=$?
	
	if [ $lrs != 0 ]; then
	    WARN "Installation has no permissions to write to destination directory."
	    RS="$path"
	    return 1
	fi

    if [ -n "$needed_space" ]; then
	    CHECK_FREE_SPACE "$path" $needed_space
	    lrs=$?
	
	    if [ $lrs != 0 ]; then
	        WARN "Specified filesystem has no enough free space ($needed_space Mb)."
		    RS="$path"
	        return 1
	    fi
    fi

	lrs=1
	if [ -e "$path" ]; then
		if [ -d "$path" ]; then
			if [ "1" = "$RPM_INSTALLATION" ]; then
				owner=$(rpm -qf $path 2>/dev/null)
				lrs=$?
				[ "$lrs" = "0" ] && summary=$(rpm -q "$owner" --qf %{summary} )
				[ -z "$summary" ] && summary=$owner
			fi
			if [ $lrs != 0 ]; then
				NONRPM_DB_FIND_BY_INSTALLDIR "$path"
				local owner=$RS
				if [ "x$owner" != "x" ]; then
					NONRPM_DB_GET_RPMBASED_FIELD $owner "SUMMARY"
					local rst=$?
					summary=$RS
		                        [ $rst = 0 ] || summary="$owner"
					lrs=0
				else
				        lrs=1
				fi
			fi
			if [ $lrs = 0 ]; then
				[ "$verbose" != "1" ] && WARN "Destination directory is already exist and owned by $summary."
				RS="$path"
				return 1
			else
				if [ "$verbose" != "1" ]; then 
                    WARN "Destination directory is already exist."
				    RS="$path"
				    return 2
                fi
			fi
        fi
	fi
	
	RS="$path"	
		
	return 0
}
	




UNINSTALL_RPM(){

	local ChosenRPM=$1
	shift
	local uninstall_options=$@
	local fcode=$ERR_OK

	RPM_CONFIG
	    
	local pack_ver=`RPM_INFO $ChosenRPM VERSION`
	fcode=$?
    
	[ $fcode -eq ${ERR_OK} ] || return $fcode
    
	MAKE_TEMP_FILE
    	local TEMPFILE=$RS
	local err=$?
	[ $err -eq ${ERR_OK} ] || return $err
	
	rpm -vv -e $ChosenRPM $uninstall_options > $TEMPFILE 2>&1
	local err=$?
	
	if [ $err -ne 0 ] ; then 
		local RPM_LOGS=$(sed 's/^/    /g' $TEMPFILE)
		LOG "Uninstallation of the $ChosenRPM. RPM logs: \n$RPM_LOGS"
		fcode=$ERR_RPM_UNINSTALL
	else
		LOG "Uninstallation of the $ChosenRPM has succeeded."
		fcode=${ERR_OK}
	fi # if [ ! "$RPMERROR" = 0 ] ; then 

	rm -f $TEMPFILE
	RS=$fcode
	return $fcode

} #UNINSTALL_RPM(){






CHECK_COMMANDS(){
    [ -n "$(which sed 2>/dev/null)" ] || DIE "Unable to find 'sed' command, please add its location to your PATH."

    local CHECK_CMD=$(echo "sed egrep id groupmod groupadd groupdel mktemp rpm rm tr mkdir rmdir readlink cp chmod uniq uname wc cut basename date cpio find cat tac ls gunzip" | sed -e"s/rpm //g")
    local c=''
    for c in ${CHECK_CMD} ; do
        which $c >/dev/null 2>&1
        if [ $? -ne 0 ] ; then
            if [ -f "/etc/mvl-release" ] && [ "chkconfig" = "$c" ] ; then
                : # there is no chkconfig command on MontaVista* CGE Linux*
            else
                echo "ERROR: unable to find command '$c'."
                echo "Please add the location to the above commands to your PATH and re-run the script"
                echo -n "Press Enter to continue."
                WAIT_ENTER_KEY
                exit 1
            fi
        fi
    done
}

ERR_OK=0

ERR_GROUP=10
	ERR_GROUP_NOT_EXISTS=11
	ERR_GROUP_EXISTS=12
	ERR_RPM_INSTALL=13
	ERR_UNKNOWN_ARC=14
	ERR_RPM_LOCK=15
	ERR_RPM_NO_PACKAGE=16
	ERR_RPM_UNINSTALL=17
	ERR_RPM_NOT_RELOCATABLE=18

LOG_F=
	TELL_WIDTH=80
	_SET_FMT_=
	RS=
	RA=
	CONFIG_FILENAME=''
	CONFIG=''
	PLATFORM=''
	IA=''
	RPM_CHECK=0
	CMD_STR=''
	RPM_CONFIGURED=-1




INSTALL_RPM(){

	local prefix="$3"
	local ChosenRPM="$1"
	shift
	local options="$1"
	local fcode=$ERR_OK
	
	LOG "Install rpm - $ChosenRPM"
	LOG "Options are: '$options'."

	
	RPM_CONFIG
	
	local opt_2=
	local prefix=`echo "$prefix" | sed s@--prefix[[:space:]]*@@`
	
	if echo $prefix | egrep "^\"" >/dev/null 2>&1 ; then
		prefix=`echo "$prefix" | cut -d'"' -f2`
		opt_2=`echo "$options" | sed s@--prefix[[:space:]]*"$prefix"@@`
	else
		prefix=`echo "$prefix" | cut -d' ' -f1`
		opt_2=`echo "$options" | sed s@--prefix[[:space:]]*$prefix@@`
	fi
	
	
	local rpm_name=`RPM_INFO "$ChosenRPM" NAME`
	fcode=$?
	

	if [ $fcode -ne ${ERR_OK} ]; then
		return $fcode
	fi # if [ $? -ne ${ERR_OK} ]; then
    
    
    
	MAKE_TEMP_FILE
	local TEMPFILE="$RS"
	local err=$?
	[ $err -eq ${ERR_OK} ] || return $err
	
	if [ ${RPM_CONFIGURED} -eq ${ERR_RPM_NOT_RELOCATABLE} ] || [ "x$prefix" = "x" ]; then
		LOG "Using rpm install without relocation."
		rpm $opt_2 -vv $ChosenRPM > $TEMPFILE 2>&1
		err=$?
	else
		LOG "Using rpm install with relocation to '$prefix'"
		rpm $opt_2 -vv --prefix "$prefix" "$ChosenRPM" > $TEMPFILE 2>&1 
		err=$?
	fi # if [ ${RPM_CONFIGURED} -eq ${ERR_RPM_NOT_RELOCATABLE} ] ; then
	
	if [ $err -ne 0 ] ; then 
		fcode=$ERR_RPM_INSTALL
		local logs=$(sed 's/^/    /g' $TEMPFILE)
		LOG "Installation of $ChosenRPM. Logs are: "
		LOG "\n${logs}"
    	else
		LOG "'$ChosenRPM' installed"
	fi #if [ $err -ne 0 ] ; then
	
	rm -f "$TEMPFILE" >/dev/null 2>&1

	return $fcode
} #INSTALL_RPM(){





NONRPM_INSTALL_PACKAGE() {

    local rpm_path="$1"     # A path to rpm file to be installed.
    local dst_dir="$2"      # A path to directory to install package to.
    local edit_uninstall_mode=""$3	# A mode to fix uninstall script for overwrite multiply installation
    [ -z "$edit_uninstall_mode" ] && edit_uninstall_mode=1 	# To fix as per default
    local touch_dest=""$4
    [ -z "$touch_dest" ] && touch_dest=1
    local noscrits=$5

    [ -z "$dst_dir" ] && dst_dir=$("$RPM_EXTR_TOOL" -qp --qf %{PREFIXES} "$rpm_path")
    dst_dir=$(echo "$dst_dir" | sed -e"s/\/\{1,\}/\//g")
    dst_dir=$(echo "$dst_dir" | sed -e"s/\/\{1,\}$//g")
    local db="$INTEL_SDP_PRODUCTS_DB"
    local db_dir=$(dirname "$db") || DIE "Unexpected error."
    local cur_dir=$(pwd) || DIE "Unable to find current directory."
    local rpm_file=$(basename "$rpm_path") || DIE "Unexpected error."

    local rpm_prefix=$("$RPM_EXTR_TOOL" -qp --qf %{PREFIXES} "$rpm_path") \
        || DIE "Unexpected error."
    local rpm_name=$("$RPM_EXTR_TOOL" -qp --qf %{NAME} "$rpm_path") \
        || DIE "Unexpected error."
    local log_file=".$rpm_file"_$(date +'%d%m%y_%H%M%S').log \
        || DIE "Unexpected error."
    if [ -n "${TEMP_FOLDER}" ]; then
        local tmp_dir="${TEMP_FOLDER}/.install_tmp"
    else
        local tmp_dir="/tmp/.install_tmp"
    fi
    local src_dir="$tmp_dir/tmp12345qwexyz/${rpm_prefix}"

    if [ "1" = "$touch_dest" ]; then
        [ -e "$dst_dir" ] && rm -rf "$dst_dir" >/dev/null 2>&1
        [ -e "$dst_dir" ] || mkdir -p "$dst_dir" >/dev/null 2>&1
    fi

    local script_dir="$dst_dir/.scripts"
    mkdir -p "$script_dir" 
    if [ $? -ne 0 ]; then
        LOG "Can't create directory \"$script_dir\""
        exit 152;
    fi
    local script body
    for script in PREIN POSTIN PREUN POSTUN SUMMARY; do
        body=$("$RPM_EXTR_TOOL" -qp --qf "%{$script}" "$rpm_path") || DIE "Can't extract \"$script\" script"
        if [ "$body" != "(none)" ]; then
             echo "$body" > "$script_dir/$script.$rpm_name"
             if [ $? -ne 0 ]; then 
                LOG "Can't write file \"$script_dir/$script.$rpm_name\""
                exit 152; 
             fi;
        fi
    done

    if [ "$noscripts" != "1" ]; then
        if [ -e "$script_dir/PREIN.$rpm_name" ]; then
            env RPM_INSTALL_PREFIX="$dst_dir" /bin/sh "$script_dir/PREIN.$rpm_name"
            if [ $? -ne 0 ]; then
                LOG "Pre-install script failed"
                exit 151; 
            fi;
        fi
    fi

    [ -d "$tmp_dir/tmp12345qwexyz" ] && rm -rf "$tmp_dir/tmp12345qwexyz" >/dev/null 2>&1
    mkdir -p "$tmp_dir/tmp12345qwexyz" >/dev/null 2>&1
    cd "$tmp_dir/tmp12345qwexyz"

    "$RPM_EXTR_TOOL" "$cur_dir/$rpm_file" | gunzip --quiet | cpio --quiet -idmu 
    if [ $? -ne 0 ]; then
        LOG "Unable to extract files from \"$rpm_file\" to temp filebuf."
        exit 151; 
    fi;

    if [ 1 = "$edit_uninstall_mode" ]; then
		find "$tmp_dir/tmp12345qwexyz/$rpm_prefix" -name uninstall*.sh > uninstall.lst \
			|| DIE "Unexpected error."
		local lines=$( wc -l uninstall.lst | awk '{print $1;}') \
			|| DIE "Unexpected error."
		[ 1 = "$lines" ] \
			|| DIE "Unexpected error."
		rm -f lines.tmp \
			|| DIE "Unexpected error."
		local uninstall=$(cat "uninstall.lst") \
			|| DIE "Unexpected error."
		cp -p "$uninstall" "uninstall.sh.bak" \
			|| DIE "Unable to copy \"$uninstall\" file to \"uninstall.sh.bak\"."
		chmod u+w "$uninstall" \
			|| DIE "Unable to change mode on \"$uninstall\" file."
		sed s@'^RPM_INSTALLATION=1$'@'RPM_INSTALLATION='@g "uninstall.sh.bak" > "$uninstall" \
			|| DIE "Unable to write \"$uninstall\" file."
		chmod --reference="uninstall.sh.bak" "$uninstall" \
			|| DIE "Unable to change mode on \"$uninstall\" file."
		rm -f "uninstall.sh.bak" >/dev/null 2>&1
		rm -f "uninstall.lst" >/dev/null 2>&1
    fi

    "$RPM_EXTR_TOOL" "$cur_dir/$rpm_file" | gunzip --quiet | cpio --quiet -t | sed s@"^\.$rpm_prefix"@"$dst_dir"@g | sed 's/^\.//' > "$tmp_dir/tmp12345qwexyz/$log_file"
    if [ $? -ne 0 ]; then
        LOG "Unable to create log file."
        exit 151; 
    fi;
    mkdir -p "$db_dir"; 
    if [ $? -ne 0 ]; then
        LOG "Unable to create \"$db_dir\" directory."
        exit 153;
    fi;
    mv "$tmp_dir/tmp12345qwexyz/$log_file" "$db_dir" 
    if [ $? -ne 0 ]; then
        LOG "Unable to copy \"$tmp_dir/$log_file\" file to \"$db_dir\" directory."
        exit 153;
    fi;
    NONRPM_DB_ENTRY_ADD "<:$rpm_name:$rpm_file:$dst_dir:$db_dir/$log_file:>"
    if [ $? -ne 0 ]; then
        LOG "Cannot add entry to database."
        exit 153;
    fi;
    local list=$(find "$tmp_dir/tmp12345qwexyz" -type f | grep "tmp12345qwexyz$rpm_prefix" -v)
    for entry in $list; do
        cp -f $entry `echo $entry | sed 's/^.*tmp12345qwexyz//'`
    done
    cd "$src_dir" \
        || DIE "Unable to change directory to \"$src_dir\"."
    if [ 1 = "$touch_dest" ]; then
    	mv -f * "$dst_dir"
    	if [ $? -ne 0 ]; then
		    LOG "Unable to move files to \"$dst_dir\" directory."
		    exit 152;
		fi;
    else
        local list_of_files_in_rpm="$(find . -type f -printf '%p;' 2>/dev/null && find . -type l -printf '%p;' 2>/dev/null)"
        local err=0
	
	    OLD_IFS=$IFS
	    IFS=";"
        for real_file in ${list_of_files_in_rpm}; do
            local file_dir=$(dirname "$real_file")
            mkdir -p "${dst_dir}${file_dir#\.}" >/dev/null 2>&1
            if [ -f "$real_file" ] || [ -L "$real_file" ]; then
                mv -f "${real_file}" "${dst_dir}${file_dir#\.}"
                if [ -L "$real_file" ]; then
                    LOG "The file $real_file is symlink to $(readlink "$real_file")";
                fi;
            else
                LOG "The file $real_file does not exit, this should have never been printed out";
            fi;
            [ $? -ne 0 ] && err=1
        done
	    IFS=$OLD_IFS
	
        if [ $err -ne 0 ]; then 
            LOG "Problems moving files to \"$dst_dir\" directory."
            exit 152;
        fi
    fi
    rm -rf "$tmp_dir"
    cd "$cur_dir" \
        || DIE "Unable to change directory to \"$cur_dir\"."

    if [ "$noscripts" != "1" ]; then
        if [ -e "$script_dir/POSTIN.$rpm_name" ]; then
            env RPM_INSTALL_PREFIX="$dst_dir" /bin/sh "$script_dir/POSTIN.$rpm_name"
            if [ $? -ne 0 ]; then
                LOG "Post-install script failed"
                exit 151;
            fi;
        fi
    fi

    return ${ERR_OK}
} # NONRPM_INSTALL_PACKAGE



NONRPM_UNINSTALL_PACKAGE() {

    local entry="$1"
    local noscripts=$2

    if ! NONRPM_DB_ENTRY_CHECK_SYNTAX "$entry"; then
        echo "Specified db entry to uninstall does not look like a valid one. Probably, internal error."
        return 1
    fi

    NONRPM_DB_ENTRY_GET_LOGFILE "$entry"
    local log_file=$RS \
        || DIE "Unexpected error"
    if [ ! -f "$log_file" ]; then
	    echo "Uninstallation cannot continue for this component: Missing \"$log_file\"."
	    return 1
    fi

    NONRPM_DB_ENTRY_GET_INSTALLDIR "$entry"
    local install_dir=$RS \
        || DIE "Unexpected error"
    if [ ! -d "$install_dir" ]; then
	   echo "Uninstallation cannot continue for this component: Missing \"$install_dir\" directory."
	   return 1
    fi

    local script_dir="$install_dir/.scripts"
    NONRPM_DB_ENTRY_GET_FIELD "$entry" 2
    local rpm_name=$RS
    
    if [ "$noscripts" != "1" ]; then
        
        if [ -f "$script_dir/PREUN.$rpm_name" ]; then
            env RPM_INSTALL_PREFIX="$install_dir" /bin/sh "$script_dir/PREUN.$rpm_name" || DIE "Post-uninstall script failed"
        fi
    fi

    NONRPM_DB_CHECK_SHARED_FILES "$install_dir" "$log_file"
    
    if [ "$noscripts" != "1" ]; then
        if [ -f "$script_dir/POSTUN.$rpm_name" ]; then
            env RPM_INSTALL_PREFIX="$install_dir" /bin/sh "$script_dir/POSTUN.$rpm_name" || DIE "Post-uninstall script failed"
        fi
    fi

    local script
    for script in PREIN POSTIN PREUN POSTUN SUMMARY; do
        rm -f "$script_dir/$script.$rpm_name"
    done

    if [ -z "$(ls $script_dir 2>/dev/null)" ]; then
	LOG "Nonrpm script dir is emplty. Will be deleted."
	rm -rf "$script_dir"
    else
	LOG "Nonrpm script dir is not emplty."
    fi

    if [ -d "$install_dir" ]; then
        rmdir --ignore-fail-on-non-empty "$install_dir" >/dev/null 2>&1
    fi

    rm -f "$log_file"
    NONRPM_DB_ENTRY_REMOVE "$entry"

    RS=0
    return 0

} # NONRPM_UNINSTALL_PACKAGE


drv_dir_suffix="sepdk/src"
pax_dir_suffix="pax"
drv_prebuilt_dir_suffix="sepdk/prebuilt"
pax_prebuilt_dir_suffix="pax"
pwr_drv_dir_suffix="powerdk/src"
pwr_drv_prebuilt_dir_suffix="powerdk/prebuilt"

LAUNCH () {

    cla_value=$(GET_COMMAND_LINE_OPTION_VALUE "c")

    case $cla_value in
        AMPL_COMMON_NOARCH )
            LOG "Installing $cla_value ..."
            RPM_PACKAGES="$RPM_PACKAGES_COMMON_noarch" 
            ;;

        AMPL_CLI_X86 )
            LOG "Installing $cla_value ..."
            if [ $UNPACK_MODE != "0" ]; then
                LOG "Unpacking all CLI components for shared installation ..."
                RPM_PACKAGES="$RPM_PACKAGES_CLI_noarch $RPM_PACKAGES_CLI_x86 $RPM_PACKAGES_CLI_x86_64"
            else
                RPM_PACKAGES="$RPM_PACKAGES_CLI_noarch $RPM_PACKAGES_CLI_x86"
            fi
            ;;

        AMPL_CLI_X86_64 )
            LOG "Installing $cla_value ..."
            RPM_PACKAGES="$RPM_PACKAGES_CLI_noarch $RPM_PACKAGES_CLI_x86 $RPM_PACKAGES_CLI_x86_64"
            ;;

        AMPL_GUI_X86 )
            LOG "Installing $cla_value ..."
            if [ $UNPACK_MODE != "0" ]; then
                LOG "Unpacking all GUI components for shared installation ..."
                RPM_PACKAGES="$RPM_PACKAGES_GUI_noarch $RPM_PACKAGES_GUI_x86 $RPM_PACKAGES_GUI_x86_64"
            else
                RPM_PACKAGES="$RPM_PACKAGES_GUI_noarch $RPM_PACKAGES_GUI_x86"
            fi
            ;;

        AMPL_GUI_X86_64 )
            LOG "Installing $cla_value ..."
            if [ $UNPACK_MODE != "0" ]; then
                LOG "Unpacking all GUI components for shared installation ..."
                RPM_PACKAGES="$RPM_PACKAGES_GUI_noarch $RPM_PACKAGES_GUI_x86_64 $RPM_PACKAGES_GUI_x86"
            else
                RPM_PACKAGES="$RPM_PACKAGES_GUI_noarch $RPM_PACKAGES_GUI_x86_64"
            fi
            ;;

        AMPL_SEP_X86 | AMPL_SEP_X86_RELOAD )
            LOG "Installing $cla_value ..."
            if [ $UNPACK_MODE != "0" ]; then
                LOG "Unpacking all SEP components for shared installation ..."
                RPM_PACKAGES="$RPM_PACKAGES_SEP_noarch $RPM_PACKAGES_SEP_x86 $RPM_PACKAGES_SEP_x86_64"
            else
                RPM_PACKAGES="$RPM_PACKAGES_SEP_noarch $RPM_PACKAGES_SEP_x86"
            fi
            ;;

        AMPL_SEP_X86_64 | AMPL_SEP_X86_64_RELOAD )
            LOG "Installing $cla_value ..."
            RPM_PACKAGES="$RPM_PACKAGES_SEP_noarch $RPM_PACKAGES_SEP_x86 $RPM_PACKAGES_SEP_x86_64"
            ;;

        AMPL_PWR_X86 )
            LOG "Installing $cla_value ..."
            if [ $UNPACK_MODE != "0" ]; then
                LOG "Unpacking all PWR components for shared installation ..."
                RPM_PACKAGES="$RPM_PACKAGES_PWR_noarch $RPM_PACKAGES_PWR_x86 $RPM_PACKAGES_PWR_x86_64"
            else
                RPM_PACKAGES="$RPM_PACKAGES_PWR_noarch $RPM_PACKAGES_PWR_x86"
            fi
            ;;

        AMPL_PWR_X86_64 )
            LOG "Installing $cla_value ..."
            RPM_PACKAGES="$RPM_PACKAGES_PWR_noarch $RPM_PACKAGES_PWR_x86 $RPM_PACKAGES_PWR_x86_64"
            ;;

        * ) 
            echo "Invalid INSTALL_COMPONENT $cla_value"
            exit $ERROR_PACKAGE_IS_CORRUPTED
            ;;
    esac

    cla_value=$(GET_COMMAND_LINE_OPTION_VALUE "run")

    for one in $RPM_PACKAGES; do
        [ -z "$one" ] && continue;
        CHOSEN_RPM="$cla_value/$one"
        if [ ! -f "$CHOSEN_RPM" ]; then
            LOG "LAUNCH:ERROR RPM package $one has been corrupted. Installation aborted."
            exit $ERROR_PACKAGE_IS_CORRUPTED
        fi
    done

    CHOSEN_RPM="$cla_value"

    INSTALL_PRODUCT
    
    PARSE_SILENT_CONFIG_OPTIONS

    cla_value=$(GET_COMMAND_LINE_OPTION_VALUE "c")

    if [ $(echo $cla_value | grep "SEP") ]; then
        if [ $(echo $cla_value | grep "RELOAD") ]; then 
            LOG "LAUNCH: installing add-on, only reloading driver, no patching of driver scripts";
            SEP_INST_ARG=DEFAULT;
        else
            SEP_SCRIPTS_CONFIGURE
            SEP_INST_ARG=CONFIG;
        fi;

        if [ $USER_ROOT -eq 0 ]; then
            LOG "LAUNCH: driver is not processed for non-root user"
            return 0;
        fi

        SEP_DRIVER_INSTALL $SEP_INST_ARG;
    fi

    if [ $(echo $cla_value | grep "PWR") ]; then

        PWR_SCRIPTS_CONFIGURE;

        if [ $USER_ROOT -eq 0 ]; then
            LOG "LAUNCH: driver is not processed for non-root user"
            return 0;
        fi

        PWR_DRIVER_INSTALL
    fi
} # function LAUNCH

INSTALL_PRODUCT() {

    PREFIX="--prefix $DESTINATION"
    for one in $RPM_PACKAGES; do
        [ -z "$one" ] && continue;
        if [ "RPM" = "$INSTALL_MODE" ]; then
            LOG "INSTALL_PRODUCT:INFO Installing RPM package $CHOSEN_RPM/$one $DEFAULTOPTIONS $PREFIX"
            INSTALL_RPM "$CHOSEN_RPM/$one" "$DEFAULTOPTIONS" "$PREFIX" || exit $ERROR_RPM_INSTALL_FAILED
        else
            LOG "INSTALL_PRODUCT:INFO Installing NONRPM package $CHOSEN_RPM/$one $DESTINATION"
            cd $CHOSEN_RPM >/dev/null 2>/dev/null 
            NONRPM_INSTALL_PACKAGE "$one" "$DESTINATION" 0 0 || exit 1
            cd - >/dev/null 2>/dev/null
        fi
    done

    return 0
} # function INSTALL_PRODUCT

TOOLS_CHECK() {
    ARC_GET

    cla_value=$(GET_COMMAND_LINE_OPTION_VALUE "chklic-path")
    [ $? -ne 0 ] && cla_value="$EXECDIR"
    chexec_value=$(GET_COMMAND_LINE_OPTION_VALUE "chklic-exec")
    chexec_ret=$?
    [ $chexec_ret -ne 0 ] || CHKLIC_TOOL="$chexec_value"

    case "$PLATFORM" in
    "x32" )
        [ $chexec_ret -ne 0 ] && CHKLIC_TOOL="$cla_value/chklic.x32"
        RPM_EXTR_TOOL="$(dirname $CHKLIC_TOOL)/rpm_extract.ia32"
        ;;

    "x64" )
        [ $chexec_ret -ne 0 ] && CHKLIC_TOOL="$cla_value/chklic.ia64"
        RPM_EXTR_TOOL="$(dirname $CHKLIC_TOOL)/rpm_extract.ia64"
        ;;

    "x32_64" )
        [ $chexec_ret -ne 0 ] && CHKLIC_TOOL="$cla_value/chklic.x64"
        RPM_EXTR_TOOL="$(dirname $CHKLIC_TOOL)/rpm_extract.x64"
        ;;
    *)
        DIE "TOOLS_CHECK:ERROR: Unable to detect HW platform (i*86, ia64 or i86_64) to prepare install enviroment."         
        ;;
    esac

    if [ -f "$RPM_EXTR_TOOL" ]; then
        if [ ! -x "$RPM_EXTR_TOOL" ]; then
            LOG "TOOLS_CHECK:ERROR: NONRPM install tool has been corrupted. Installation aborted."
            exit $ERROR_PACKAGE_IS_CORRUPTED
        fi
    else
        LOG "TOOLS_CHECK:ERROR: NONRPM install tool has been corrupted. Installation aborted."
        exit $ERROR_PACKAGE_IS_CORRUPTED
    fi
} # function TOOLS_CHECK

PARSE_SILENT_CONFIG_OPTIONS()
{
    READ_DEFAULT_ANSWER "PSL_DRIVER_INSTALL_TYPE"
    PSL_DRIVER_INSTALL_TYPE=$RS

    READ_DEFAULT_ANSWER "PSL_PWR_DRIVER_INSTALL_TYPE"
    PSL_PWR_DRIVER_INSTALL_TYPE=$RS

    READ_DEFAULT_ANSWER "PSL_DRIVER_ACCESS_GROUP"
    PSL_DRIVER_ACCESS_GROUP=$RS

    READ_DEFAULT_ANSWER "PSL_DRIVER_ACCESS_PERM"
    PSL_DRIVER_ACCESS_PERM=$RS

    READ_DEFAULT_ANSWER "PSL_LOAD_DRIVER"
    PSL_LOAD_DRIVER=$RS

    READ_DEFAULT_ANSWER "PSL_INSTALL_BOOT_SCRIPT"
    PSL_INSTALL_BOOT_SCRIPT=$RS

    READ_DEFAULT_ANSWER "PSL_DRIVER_PER_USER_MODE"
    PSL_DRIVER_PER_USER_MODE=$RS

    READ_DEFAULT_ANSWER "PSL_C_COMPILER"
    PSL_C_COMPILER=$RS

    READ_DEFAULT_ANSWER "PSL_MAKE_COMMAND"
    PSL_MAKE_COMMAND=$RS

    READ_DEFAULT_ANSWER "PSL_KERNEL_SOURCE_DIR"
    PSL_KERNEL_SOURCE_DIR=$RS
} # function PARSE_SILENT_CONFIG_OPTIONS

SEP_SCRIPTS_CONFIGURE()
{
    PREV_MASK=$(umask)
    umask 000 >/dev/null 2>/dev/null
    FILE2CUST=$drv_dir/insmod-sep3
    if [ -r ${FILE2CUST} ] ; then
        cp ${FILE2CUST} ${FILE2CUST}.tmp
        cat ${FILE2CUST} | sed -e "s@^DEFAULT_GROUP=.*@DEFAULT_GROUP=${PSL_DRIVER_ACCESS_GROUP}@g;s@^DEFAULT_PERMS=.*@DEFAULT_PERMS=${PSL_DRIVER_ACCESS_PERM}@g" > ${FILE2CUST}.tmp
        mv ${FILE2CUST}.tmp ${FILE2CUST}
    fi

    FILE2CUST=$drv_prebuilt_dir/insmod-sep3
    if [ -r ${FILE2CUST} ] ; then
        cp ${FILE2CUST} ${FILE2CUST}.tmp
        cat ${FILE2CUST} | sed -e "s@^DEFAULT_GROUP=.*@DEFAULT_GROUP=${PSL_DRIVER_ACCESS_GROUP}@g;s@^DEFAULT_PERMS=.*@DEFAULT_PERMS=${PSL_DRIVER_ACCESS_PERM}@g" > ${FILE2CUST}.tmp
        mv ${FILE2CUST}.tmp ${FILE2CUST}
    fi

    umask $PREV_MASK

    LOG "SEP Scripts have been customized."
} # function SEP_SCRIPTS_CONFIGURE

PWR_SCRIPTS_CONFIGURE()
{
    PREV_MASK=$(umask)
    umask 000 >/dev/null 2>/dev/null
    FILE2CUST=$pwr_drv_dir/insmod-apwr
    if [ -r ${FILE2CUST} ] ; then
        cp ${FILE2CUST} ${FILE2CUST}.tmp
        cat ${FILE2CUST} | sed -e "s@^DEFAULT_GROUP=.*@DEFAULT_GROUP=${PSL_DRIVER_ACCESS_GROUP}@g;s@^DEFAULT_PERMS=.*@DEFAULT_PERMS=${PSL_DRIVER_ACCESS_PERM}@g" > ${FILE2CUST}.tmp
        mv ${FILE2CUST}.tmp ${FILE2CUST}
    fi

    FILE2CUST=$pwr_drv_prebuilt_dir/insmod-apwr
    if [ -r ${FILE2CUST} ] ; then
        cp ${FILE2CUST} ${FILE2CUST}.tmp
        cat ${FILE2CUST} | sed -e "s@^DEFAULT_GROUP=.*@DEFAULT_GROUP=${PSL_DRIVER_ACCESS_GROUP}@g;s@^DEFAULT_PERMS=.*@DEFAULT_PERMS=${PSL_DRIVER_ACCESS_PERM}@g" > ${FILE2CUST}.tmp
        mv ${FILE2CUST}.tmp ${FILE2CUST}
    fi

    umask $PREV_MASK

    LOG "PWR Scripts have been customized."
} # function PWR_SCRIPTS_CONFIGURE

CHECK_ROOT()
{
   USERID=$(id -u)
   if [ "$USERID" -ne "0" ] ; then
         USER_ROOT=0
   else
      USER_ROOT=1
   fi
} # function CHECK_ROOT

STATUS_INSMODE_QUERY_DRIVERS_ARE_LOADED="0"
STATUS_INSMODE_QUERY_DRIVERS_NOT_LOADED="212"
STATUS_INSMODE_QUERY_PAX_NOT_LOADED="214"
STATUS_INSMODE_QUERY_SEP_NOT_LOADED="213"

GET_SEP_DRIVER_ACCESS_GROUP()
{
    INSMOD_QUERY_RES=`./insmod-sep3 -q`
    INSMOD_QUERY_RET_CODE="$?"

    LOG "GET_SEP_DRIVER_ACCESS_GROUP:INFO: insmod query text results are: $INSMOD_QUERY_RES ret code:$INSMOD_QUERY_RET_CODE"

    case $INSMOD_QUERY_RET_CODE in
        $STATUS_INSMODE_QUERY_DRIVERS_ARE_LOADED | $STATUS_INSMODE_QUERY_SEP_NOT_LOADED) 
            CURRENT_DRIVER_ACCESS_GROUP=`./insmod-sep3 -q | head -1 | cut -d '"' -f2`
            CURRENT_DRIVER_ACCESS_PERM=`./insmod-sep3 -q | head -1 | cut -d '"' -f4`
            PAX_IS_LOADED="1"
            ;;

        $STATUS_INSMODE_QUERY_PAX_NOT_LOADED ) 
            CURRENT_DRIVER_ACCESS_GROUP=`./insmod-sep3 -q | tail -1 | cut -d '"' -f2`
            CURRENT_DRIVER_ACCESS_PERM=`./insmod-sep3 -q | tail -1 | cut -d '"' -f4`
            ;;

        $STATUS_INSMODE_QUERY_DRIVERS_NOT_LOADED ) 
            CURRENT_DRIVER_ACCESS_GROUP=""
            CURRENT_DRIVER_ACCESS_PERM=""
            ;;

        * ) 
            LOG "GET_SEP_DRIVER_ACCESS_GROUP:ERROR: insmod query return error status $INSMOD_QUERY_RET_CODE"
            CURRENT_DRIVER_ACCESS_GROUP=""
            CURRENT_DRIVER_ACCESS_PERM=""
            ;;
    esac
} # function GET_SEP_DRIVER_ACCESS_GROUP

DRIVER_BUILD_OPTION_VALID()
{
    local VALID='0'

    if [ "${PSL_KERNEL_SOURCE_DIR}" = 'none' ] ; then
        LOG "DRIVER_BUILD_OPTION_VALID:ERROR The 'Kernel Source Directory' option is 'none'"
        VALID=1
    fi

    if [ "${PSL_C_COMPILER}" = 'none' ] ; then
        LOG "DRIVER_BUILD_OPTION_VALID:ERROR The 'C compiler to use' option is 'none'"
        VALID=1
    fi

    if [ "${PSL_MAKE_COMMAND}" = 'none' ] ; then
        LOG "DRIVER_BUILD_OPTION_VALID:ERROR The 'Make command to use' option is 'none'"
        VALID=1
    fi

    [ "${VALID}" = "1" ] && LOG "DRIVER_BUILD_OPTION_VALID:ERROR To set the option(s) use 'Driver build options' menu"
    return ${VALID}
} # function DRIVER_BUILD_OPTION_VALID


SEP_DRIVER_INSTALL()
{
    if [ "${PSL_DRIVER_INSTALL_TYPE}" = "3" ] ; then
        LOG "SEP_DRIVER_INSTALL: No driver operations are required by user choice. Returning ok."
        return 0;
    fi

    SMP=`uname -v | grep SMP`
    if [ -z "$SMP" ]; then
        ARITY="up"
    else
        ARITY="smp"
    fi
    LOG "SEP_DRIVER_INSTALL:INFO: Kernel is ${ARITY}"

    PSL_ADD_GROUP

    LOG "SEP_DRIVER_INSTALL:INFO: Driver build directory is equal to: $drv_dir"
    cd $drv_dir >/dev/null 2>/dev/null

    DRIVER_NAME=$(bash ./build-driver --print-driver-name)
    cd - >/dev/null 2>/dev/null

    LOG "SEP_DRIVER_INSTALL:INFO: Ready to install the driver: $DRIVER_NAME"

    if [ "${PSL_DRIVER_INSTALL_TYPE}" = "2" ] ; then
        DRIVER_BUILD_OPTION_VALID
        if [ "$?" != "0" ]; then
            exit $WARNING_BUILD_DRIVER_OPTIONS_ARE_NOT_VALID;
        fi

        BUILD_DRIVER "SEP"
        if [ "$?" != "0" ]; then
            exit $WARNING_FAILED_TO_BUILD_DRIVER;
        fi

        LOG "SEP_DRIVER_INSTALL:INFO: Using drivers from build directory. "
        cd $drv_dir >/dev/null 2>/dev/null
    else
        LOG "SEP_DRIVER_INSTALL:INFO: Using drivers from pre-built directory. "
        cd $drv_prebuilt_dir >/dev/null 2>/dev/null
    fi

    if [ "${PSL_LOAD_DRIVER}" = "1" ] ; then
        LOG "SEP_DRIVER_INSTALL:INFO: Loading the driver ... "

        GET_SEP_DRIVER_ACCESS_GROUP
        if [ "$PSL_DRIVER_ACCESS_GROUP" != "$CURRENT_DRIVER_ACCESS_GROUP" ] ||
           [ "$PSL_DRIVER_ACCESS_PERM" != "$CURRENT_DRIVER_ACCESS_PERM" ]; then
                LOG 'SEP_DRIVER_INSTALL:INFO: User and loaded driver access groups and/or permissions are not matching. '
                LOG "Current group: $CURRENT_DRIVER_ACCESS_GROUP User group:$PSL_DRIVER_ACCESS_GROUP"
                LOG "Current perms: $CURRENT_DRIVER_ACCESS_PERM User perms:$PSL_DRIVER_ACCESS_PERM"
                if [ "$PAX_IS_LOADED" = "1" ]; then
                      LOG "SEP_DRIVER_INSTALL:INFO: PAX driver is loaded - stopping PAX (to reload with appropriate group) ..."
                    ./pax/rmmod-pax >> $INSTALL_LOG_FILE 2>&1
                    RET_CODE="$?"

                    if [ $RET_CODE != "0" ]; then
                        LOG "SEP_DRIVER_INSTALL:ERROR: Failed to stop PAX driver. Ret code: $RET_CODE"
                        exit $WARNING_FAILED_TO_UNLOAD_PREVIOSLY_LOADED_DRIVER
                    else
                        LOG "SEP_DRIVER_INSTALL:INFO: PAX Driver was successfully stopped. "
                    fi
                fi
        fi

        LOG "SEP_DRIVER_INSTALL:INFO: Stopping previously loaded SEP3 driver (if any) ..."
        ./rmmod-sep3 >> $INSTALL_LOG_FILE 2>&1
        RET_CODE="$?"

        if [ $RET_CODE != "0" ]; then
            LOG "SEP_DRIVER_INSTALL:ERROR: Failed to stop sampling driver. Ret code: $RET_CODE"
            exit $WARNING_FAILED_TO_UNLOAD_PREVIOSLY_LOADED_DRIVER
        else
            LOG "SEP_DRIVER_INSTALL:INFO: Sampling driver was successfully stopped (if was started before). "
        fi

        local LOAD_OPTS=""
        if [ "$PSL_DRIVER_PER_USER_MODE" = "1" ]; then
            LOAD_OPTS="-pu"
        fi

        if [ "DEFAULT" = $1 ]; then
            LOG "SEP_DRIVER_INSTALL:INFO: Starting script insmod-sep3 with no parameters because installing add-on"
            ./insmod-sep3 >> $INSTALL_LOG_FILE 2>&1
            RET_CODE="$?"
        else
            LOG "SEP_DRIVER_INSTALL:INFO: Starting script insmod-sep3 -g ${PSL_DRIVER_ACCESS_GROUP} -p ${PSL_DRIVER_ACCESS_PERM} $LOAD_OPTS"
            ./insmod-sep3 -g $PSL_DRIVER_ACCESS_GROUP -p $PSL_DRIVER_ACCESS_PERM $LOAD_OPTS >> $INSTALL_LOG_FILE 2>&1
            RET_CODE="$?"
        fi;

        if [ $RET_CODE = "0" ]; then
            LOG "SEP_DRIVER_INSTALL:INFO: Driver is loaded successfully. "
        elif [ $RET_CODE = "227" ]; then
            NMI_WATCHDOG_ENABLED=true;
            LOG "SEP_DRIVER_INSTALL:WARNING: NMI watchdog enabled. Ret code: $RET_CODE; deferred exit"
        else
            LOG "SEP_DRIVER_INSTALL:ERROR: Failed to load sampling driver. Ret code: $RET_CODE"
            exit $WARNING_FAILED_TO_LOAD_DRIVER
        fi
    fi

    if [ "${PSL_INSTALL_BOOT_SCRIPT}" = "1" ] ; then

        LOG "SEP_DRIVER_INSTALL:INFO: Installing sampling driver boot script ... "
        if [ "$PSL_DRIVER_PER_USER_MODE" = "1" ]; then
            ./boot-script --install -pu >> $INSTALL_LOG_FILE 2>&1
        else
            ./boot-script --install >> $INSTALL_LOG_FILE 2>&1
        fi

        RET_CODE="$?"
        if [ $RET_CODE != "0" ]; then
            LOG "SEP_DRIVER_INSTALL:ERROR: failed to install sampling driver boot script.Ret code: $RET_CODE"
            exit $WARNING_FAILED_TO_INSTALL_BOOT_SCRIPT
        else
            LOG "SEP_DRIVER_INSTALL:INFO: sampling driver boot script was successfully loaded."
        fi
    fi

    cd - >/dev/null 2>/dev/null
    if [ -n "$NMI_WATCHDOG_ENABLED" ]; then
        exit $WARNING_NMI_WATCHDOG_ENABLED
    fi;
    
    return 0
} # function SEP_DRIVER_INSTALL

PWR_DRIVER_INSTALL()
{
    if [ "${PSL_PWR_DRIVER_INSTALL_TYPE}" = "3" ] ; then
        LOG "PWR_DRIVER_INSTALL: No driver operations are required by user choice. Returning ok."
        return 0;
    fi

    SMP=`uname -v | grep SMP`
    if [ -z "${SMP}" ] ; then
        ARITY="up"
    else
        ARITY="smp"
    fi
    LOG "PWR_DRIVER_INSTALL:INFO: Kernel is ${ARITY}"

    PSL_ADD_GROUP

    LOG "PWR_DRIVER_INSTALL:INFO: Driver build directory is equal to: $pwr_drv_dir"
    cd $pwr_drv_dir >/dev/null 2>/dev/null

    DRIVER_NAME=$(bash ./build-driver --print-driver-name)
    cd - >/dev/null 2>/dev/null

    LOG "PWR_DRIVER_INSTALL:INFO: Ready to install the driver: $DRIVER_NAME"

    if [ "${PSL_PWR_DRIVER_INSTALL_TYPE}" = "2" ] ; then
        DRIVER_BUILD_OPTION_VALID
        if [ "$?" != "0" ]; then
            exit $WARNING_PWR_BUILD_DRIVER_OPTIONS_ARE_NOT_VALID;
        fi

        BUILD_DRIVER "PWR"
        if [ "$?" != "0" ]; then
            exit $WARNING_PWR_FAILED_TO_BUILD_DRIVER;
        fi

        LOG "PWR_DRIVER_INSTALL:INFO: Using drivers from build directory. "
        cd $pwr_drv_dir >/dev/null 2>/dev/null
    else
        LOG "PWR_DRIVER_INSTALL:INFO: Using drivers from pre-built directory. "
        cd $pwr_drv_prebuilt_dir >/dev/null 2>/dev/null
    fi

    if [ "${PSL_LOAD_DRIVER}" = "1" ] ; then
            LOG "PWR_DRIVER_INSTALL:INFO: Loading the driver ... "

            LOG "PWR_DRIVER_INSTALL:INFO: Stopping previously loaded PWR driver (if any) ..."
            ./rmmod-apwr >> $INSTALL_LOG_FILE 2>&1
            RET_CODE="$?"

            if [ $RET_CODE != "0" ]; then
                LOG "PWR_DRIVER_INSTALL:ERROR: Failed to stop power driver. Ret code: $RET_CODE"
                exit $WARNING_PWR_FAILED_TO_UNLOAD_PREVIOSLY_LOADED_DRIVER
            else
                LOG "DRIVER_INSTALL:INFO: Power driver was successfully stopped (if was started before). "
            fi

            LOG "PWR_DRIVER_INSTALL:INFO: Starting script ..../insmod-apwr -g ${PSL_DRIVER_ACCESS_GROUP} -p $PSL_DRIVER_ACCESS_PERM "
            ./insmod-apwr -g $PSL_DRIVER_ACCESS_GROUP -p $PSL_DRIVER_ACCESS_PERM >> $INSTALL_LOG_FILE 2>&1
            RET_CODE="$?"
            
            if [ $RET_CODE != "0" ]; then
                LOG "PWR_DRIVER_INSTALL:ERROR: Failed to load power driver. Ret code: $RET_CODE"
                exit $WARNING_PWR_FAILED_TO_LOAD_DRIVER
            else
                LOG "DRIVER_INSTALL:INFO: Driver is loaded successfully. "
            fi
    fi

    if [ "${PSL_INSTALL_BOOT_SCRIPT}" = "1" ] ; then

        LOG "DRIVER_INSTALL:INFO: Installing power driver boot script ... " 
        ./boot-script --install >> $INSTALL_LOG_FILE 2>&1
        RET_CODE="$?"

        if [ $RET_CODE != "0" ]; then
            LOG "PWR_DRIVER_INSTALL:ERROR: failed to install power driver boot script.Ret code: $RET_CODE"
            exit $WARNING_PWR_FAILED_TO_INSTALL_BOOT_SCRIPT
        else
            LOG "PWR_DRIVER_INSTALL:INFO: power driver boot script was successfully loaded."
        fi
    fi

    cd - >/dev/null 2>/dev/null
    return 0
} # function PWR_DRIVER_INSTALL

PSL_ADD_GROUP()
{
    CHECK_GROUP_EXISTS "$PSL_DRIVER_ACCESS_GROUP"
    [ "$?" = "${ERR_OK}" ] && LOCAL_GROUP_EXISTS="yes"

    CHECK_NIS_GROUP_EXISTS "$PSL_DRIVER_ACCESS_GROUP"
    [ "$?" = "${ERR_OK}" ] && NIS_GROUP_EXISTS="yes"

    if [ "$LOCAL_GROUP_EXISTS" != "yes" ] && [ "$NIS_GROUP_EXISTS" != "yes" ] ; then
        groupadd "$PSL_DRIVER_ACCESS_GROUP" >/dev/null 2>/dev/null
        EXIT_CODE=$?
        if [ "$EXIT_CODE" = "0" ]; then
            LOG "PSL_ADD_GROUP:INFO Created new group \"$PSL_DRIVER_ACCESS_GROUP\"."
        elif [ "$EXIT_CODE" = "9" ] ; then
            LOG "PSL_ADD_GROUP:WARNING Group is non-unique \"$PSL_DRIVER_ACCESS_GROUP\"."
        else
            LOG "PSL_ADD_GROUP:ERROR The installer was unable to create new group \"$PSL_DRIVER_ACCESS_GROUP\". EXIT CODE = ${EXIT_CODE}"
            exit $WARNING_UNABLE_TO_CREATE_DRIVER_ACCESS_GROUP;
        fi
    else
       LOG "PSL_ADD_GROUP:INFO Group \"$PSL_DRIVER_ACCESS_GROUP\" is already exist."
    fi
} # function PSL_ADD_GROUP

BUILD_DRIVER()
{
    local type="$1"

    driver_dir=""

    if [ "PWR" = "$type" ]; then
        driver_dir=$pwr_drv_dir
    elif [ "SEP" = "$type" ]; then
        driver_dir=$drv_dir
    else
        LOG "BUILD_DRIVER: driver type is either not given or invalid";
        exit $WARNING_FAILED_TO_BUILD_DRIVER;
    fi

    cd $driver_dir >/dev/null 2>/dev/null

    local OPTS="--install-dir=$driver_dir "
    OPTS="$OPTS --kernel-src-dir=${PSL_KERNEL_SOURCE_DIR} --c-compiler=${PSL_C_COMPILER} "
    OPTS="$OPTS --make-command=${PSL_MAKE_COMMAND} --non-interactive "
    if [ "SEP" = "$type" ] && [ "1" = "$PSL_DRIVER_PER_USER_MODE" ]; then
        OPTS="$OPTS -pu";
    fi
    
    LOG "BUILD_DRIVER:INFO:Building the $type driver for your kernel ... ./build-driver $OPTS "

    ./build-driver $OPTS >> ${INSTALL_LOG_FILE} 2>&1
    EXIT_CODE=$? 

    if [ $EXIT_CODE -eq 0 ]; then
        LOG "BUILD_DRIVER:INFO: $type Driver was successfully built."
    else
        LOG "BUILD_DRIVER:ERROR: $type Driver compilation failed. For more details, please see ${INSTALL_LOG_FILE} EXIT CODE = $EXIT_CODE"        
    fi

    cd - >/dev/null 2>/dev/null

    return $EXIT_CODE
} # function BUILD_DRIVER

WARNING_BUILD_DRIVER_OPTIONS_ARE_NOT_VALID="40"
WARNING_FAILED_TO_BUILD_DRIVER="41"
WARNING_FAILED_TO_LOAD_DRIVER="42"
WARNING_FAILED_TO_INSTALL_BOOT_SCRIPT="43"
WARNING_FAILED_TO_UNLOAD_PREVIOSLY_LOADED_DRIVER="44"
WARNING_UNABLE_TO_CREATE_DRIVER_ACCESS_GROUP="45"
WARNING_NMI_WATCHDOG_ENABLED="46"

ERROR_PACKAGE_IS_CORRUPTED="151"
ERROR_RPM_INSTALL_FAILED="152"

WARNING_PWR_BUILD_DRIVER_OPTIONS_ARE_NOT_VALID="50"
WARNING_PWR_FAILED_TO_BUILD_DRIVER="51"
WARNING_PWR_FAILED_TO_LOAD_DRIVER="52"
WARNING_PWR_FAILED_TO_INSTALL_BOOT_SCRIPT="53"
WARNING_PWR_FAILED_TO_UNLOAD_PREVIOSLY_LOADED_DRIVER="54"


CONFIG_PREFIX='piersol'
CONFIG_SECTION='piersol'

RPM_PACKAGES_COMMON_noarch=" intel-vtune-amplifier-xe-common-295420-13.1-9.noarch.rpm";

RPM_PACKAGES_CLI_noarch=" intel-vtune-amplifier-xe-cli-common-295420-13.1-9.noarch.rpm intel-vtune-amplifier-xe-doc-295420-13.1-9.noarch.rpm intel-vtune-amplifier-xe-collector-target_x86_64-295420-13.1-9.noarch.rpm intel-vtune-amplifier-xe-collector-target_ia32-295420-13.1-9.noarch.rpm";
RPM_PACKAGES_CLI_x86=" intel-vtune-amplifier-xe-cli-295420-13.1-9.i486.rpm";
RPM_PACKAGES_CLI_x86_64=" intel-vtune-amplifier-xe-cli-295420-13.1-9.x86_64.rpm";

RPM_PACKAGES_GUI_noarch=" intel-vtune-amplifier-xe-gui-common-295420-13.1-9.noarch.rpm";
RPM_PACKAGES_GUI_x86=" intel-vtune-amplifier-xe-gui-295420-13.1-9.i486.rpm";
RPM_PACKAGES_GUI_x86_64=" intel-vtune-amplifier-xe-gui-295420-13.1-9.x86_64.rpm";

RPM_PACKAGES_SEP_noarch=" intel-vtune-amplifier-xe-sep-295420-13.1-9.noarch.rpm";
RPM_PACKAGES_SEP_x86="";
RPM_PACKAGES_SEP_x86_64="";

RPM_PACKAGES_PWR_noarch=" intel-vtune-amplifier-xe-pwr-295420-13.1-9.noarch.rpm";
RPM_PACKAGES_PWR_x86="";
RPM_PACKAGES_PWR_x86_64="";

SAVE_COMMAND_LINE $@
IS_COMMAND_LINE_OPTION_EXISTS run || DIE "This script installs product and should be called from general install script. Exiting..."

SCRIPT="$0"
EXECDIR=$(dirname "$SCRIPT")
ABS_PATH "$EXECDIR"
EXECDIR="$RS"

DEFAULTOPTIONS='-ivh --force --nodeps --ignorearch'
INSTALL_MODE="RPM"


PATH="/sbin:/usr/sbin:/bin:/usr/bin/:/usr/local/sbin:/usr/local/bin:/usr/local/gnu/bin:${PATH}:"
export PATH

umask 0022

CHECK_ROOT

SET_CONFIG_FILE

if [ $USER_ROOT -eq 1 ]; then
    NONRPM_DB_PREFIX=/opt/intel
else
    NONRPM_DB_PREFIX="$HOME/intel"
fi

CONFIG_GET_VALUE $CONFIG_PREFIX $CONFIG_SECTION "INSTALLMODE"
imode=$RS
if [ "NONRPM" = "$imode" ]; then
    INSTALL_MODE="NONRPM"
    INSTALL_LOG_FILE=~/vtune_amplifier_xe_2013_install.log

    NONRPM_SET_DB_MODE
else
    INSTALL_MODE="RPM"
    INSTALL_LOG_FILE=/var/log/vtune_amplifier_xe_2013_install.log
fi

log_value=$(GET_COMMAND_LINE_OPTION_VALUE "l")
TEMP_FOLDER=$(GET_COMMAND_LINE_OPTION_VALUE "t")

INSTALL_LOG_FILE=$log_value

INIT_LOG "$log_value"

LOG "MAIN: Temp folder is equal to $TEMP_FOLDER"

TOOLS_CHECK
cla_value=""
cla_value=$(GET_COMMAND_LINE_OPTION_VALUE "installpath")
[ $? -eq 0 ] && CONFIG_SET_VALUE $CONFIG_PREFIX $CONFIG_SECTION "INSTALL_DESTINATION" $cla_value

CONFIG_GET_VALUE $CONFIG_PREFIX $CONFIG_SECTION "INSTALL_DESTINATION"
DESTINATION=$RS
drv_dir="${DESTINATION}/$drv_dir_suffix"   
drv_prebuilt_dir="${DESTINATION}/$drv_prebuilt_dir_suffix"
pwr_drv_dir="${DESTINATION}/$pwr_drv_dir_suffix"   
pwr_drv_prebuilt_dir="${DESTINATION}/$pwr_drv_prebuilt_dir_suffix"

LOG "MAIN: Installation mode is equal to $INSTALL_MODE."
[ "RPM" = "$INSTALL_MODE" ] && RPM_CONFIG

CONFIG_GET_VALUE $CONFIG_PREFIX $CONFIG_SECTION "UNPACK_MODE"
UNPACK_MODE=$RS

LAUNCH

LOG "MAIN: Installation has been finished successfully."

exit 0
