#! /bin/bash


### NOTES ON BASH ###

### when declaring var local in function, the scope extend to it childre
### defined outside and called insed and defined inside and called inside.

### only returns allowed from functions, exists to be done only in main script

### what is the story about local and globals, the approach here is that avoid locals in the functions
### unless the function can be applied more generally across different situations, parameters are needed, 
### although, strictly speaking, not really, but ..., otherwise use globals

### 

### END NOTES ON BASH ###

##############################################################

#. /nn/bin/vars-softinv.sh

DEBUG=TRUE
#DEBUG=FALSE
PATH=/opt/bin:/usr/local/bin:/usr/bin:/nn/bin:/nn/sbin:$PATH
NL="\n"

### NEW GLOBS STARTs - consolidation
##############################################################
AWK=`which awk` || AWK=/opt/bin/awk
SED=`which sed` || SED=/bin/sed
GREP=`which grep` || GREP=/bin/grep

RM=`which rm` || RM=/bin/rm
LS=`which ls` || LS=/bin/ls
TOUCH=`which touch` || TOUCH=/bin/touch
ECHO=`which echo` || ECHO=/bin/echo
CP=`which cp` || CP=/bin/cp
NICE=`which nice` || NICE=/bin/nice
DATE=`which date` || DATE=/bin/date
WGET=`which wget` || WGET=/usr/bin/wget
RPM=`which rpm` || RPM=/usr/local/bin/rpm
SMBCLIENT=`which smbclient` || SMBCLIENT=/opt/bin/smbclient
CPIO=`which cpio` || CPIO=/opt/bin/cpio
MKTEMP=`which mktemp` || MKTEMP=/bin/mktemp
RPMCOMP=`which rpmcompare` || /nn/bin/rpmcompare
WC=`which wc` || /usr/bin/wc
MKDIR=`which mkdir` || /bin/mkdir

GAP=`which GapCyperFile` || GAP=/nn/sbin/GapCyperFile
ADDNNUDIAGLOG=`which AddNnuDiagLog` || ADDNNUDIAGLOG=/nn/bin/AddNnuDiagLog


### these globs initialized elsewhere
ARCH=
SCAN_ERR_MSG=
BUILD_ERR_MSG=
DATE_ERR_MSG=
DWNLD_ERR_MSG=
APPLY_ERR_MSG=
FROM_APPLY=FALSE
### NEW GLOBS ENDs


############ EXIT CODE GLOBALS ###############################
#
ftp_ERROR=11

### this is really download error
APPLY_ERROR1=12

APPLY_ERROR=13
APPLY_ERROR_1=131
APPLY_ERROR_2=132
APPLY_ERROR_3=133
APPLY_ERROR_4=134

DONLY_ERROR=14
AONLY_ERROR=15
RBACK_ERROR=16

SCHED_ERROR=17
SCHED_ERROR_1=171
SCHED_ERROR_2=172
SCHED_ERROR_3=173
SCHED_ERROR_4=174
SCHED_ERROR_5=175

wget_ERROR=0
ERROR_WGET_PATH=26
ERROR_WGET_HOST=27
ERROR_WGET_LOGIN=28
ERROR_WGET_GEN=29
ERROR_RPM_GEN=30

MSCHED_ERROR=18
http_ERROR=19
httpS_ERROR=20
samba_ERROR=21
usb_ERROR=22
BUILD_LIST_ERROR=23
PATH_ERR=24
CRED_ERR=25
KEY="1234567890"
em_ERROR=33
smb_ERROR=0
ERROR_DATE_TZ=34
RSCHED_ERROR=35

# Save a copy of the RPM database whenever it gets updated. 
# To be used after every write operation - i.e. after any "rpm -Uvvh".
save_rpm_if_good () {
   systemrelease=`$RPM -q system-release`
   rc1=$?
   cartridge=`$RPM -q bcmEMcartridge`
   rc2=$?
   rpmlist=`$RPM -qa 2>/dev/null`
   rc3=$?
   rpmcount=`$ECHO $rpmlist | $WC -w`
   if (($rc1 == 0)) && (($rc2 == 0)) && (($rc3 == 0 )) && [[ $systemrelease == system-release*  && $cartridge == bcmEMcartridge* ]] && (($rpmcount > 265 )); then
      # Looks good.
      $MKDIR /var/local/lib/rpm/LastKnownGood 2>/dev/null
      $CP -f  /var/local/lib/rpm/[^_]* /var/local/lib/rpm/LastKnownGood 2>/dev/null
   else
      # This is a bad situation. We have just updated the RPM db, and it is now damaged. Must have been something *we* did.
      # Making the best of this: let's raise an alarm and revert to the previous DB right away.
      # Also, returning a non-zero retcode will signal the caller to abandon the present update.
      write_alarm R E 2108 'The current update has resulted in inconsistencies within the RPM Database.'
      $CP -f /var/local/lib/rpm/LastKnownGood/* /var/local/lib/rpm 2>/dev/null
      $RM -f /var/local/lib/rpm/__db* 2>/dev/null
      $RPM --rebuilddb 2>/dev/null
      if (( $? != 0 )); then
         write_alarm R E 2108 'The backup RPM database is inconsistent and cannot be relied upon.'
      fi
      return 1
   fi
   return 0
}


# Check whether the RPM database is unhealthy.
# To be used before every read operation - i.e. called whenever softinv is invoked.
# If the DB is bad, swap in a good copy. If it is OK, make a backup copy.
replace_rpm_if_necessary () {
   systemrelease=`$RPM -q system-release`
   rc1=$?
   cartridge=`$RPM -q bcmEMcartridge` 
   rc2=$?
   rpmlist=`$RPM -qa 2>/dev/null`
   rc3=$?
   rpmcount=`$ECHO $rpmlist | $WC -w`
   if (($rc1 != 0)) || (($rc2 != 0)) || (($rc3 != 0)) || [[ $systemrelease != system-release*  || $cartridge != bcmEMcartridge* ]] || (($rpmcount <= 265 )); then
      if [[ -e /var/local/lib/rpm/LastKnownGood ]]; then
         # Looks bad.
         $CP -f /var/local/lib/rpm/LastKnownGood/* /var/local/lib/rpm 2>/dev/null
         $RM -f /var/local/lib/rpm/__db* 2>/dev/null
         $RPM --rebuilddb 2>/dev/null
         if (( $? != 0 )); then
            write_alarm R E 2108 'The backup RPM database is inconsistent and cannot be relied upon.'
         else
            write_alarm R I 2107 'RPM Database has been refreshed.'
         fi
      else
         write_alarm R E 2108 'The main RPM database is inconsistent, and no backup database was found.'
      fi
   else
      $MKDIR /var/local/lib/rpm/LastKnownGood 2>/dev/null
      $CP -f  /var/local/lib/rpm/[^_]* /var/local/lib/rpm/LastKnownGood 2>/dev/null
   fi
   return 0
}


############# --- REWORK THIS TO USE $MACHTYPE --- ???
get_arch () {
    local _arch=$1

    local _local_arch=

    local _local_arch=$(uname -a | $AWK '{print $11}') || return 1

    if [ "X$_local_arch" == "Xi686" ]; then
        _local_arch="i386"
    fi

    if [ "X$_local_arch" != "Xi386" ] && [ "X$_local_arch" != "Xppc" ] ; then
        return 1
    fi
 
    eval "${_arch}=\"${_local_arch}\""
 
    return 0

}

#. /nn/bin/scan-softinv.sh

##################
make_temp_dir () {
    local _tmp_dir=$1
    local _err_msg=$2

    local _exit_code=

    local _tmp=`$MKTEMP -q -d /tmp/${PROGNAME}.XXXXXX`; _exit_code=$?
    if [ ! $_exit_code -eq 0 ]; then
        eval "${_tmp_dir}=\"\""
        eval "${_err_msg}=\"System_Error $MKTEMP Problem creating temporary directory\""
        return 1
    fi
    
    eval "${_tmp_dir}=\"${_tmp}\""
    eval "${_err_msg}=\"\""

    return 0
}

#######################
download_umds_uxds () {

    local _error_msg=
    local _exit_code=

    if ! make_temp_dir _TMP_DIR _error_msg; then
        SCAN_ERR_MSG="$_error_msg "
        return 2
    fi

    write_status "$LOGDIR/active.status" "Downloading_Patches Index File"
    info_log "Downloading Index File from $_ipaddr in $_rpath "

    $WGET -np -P ${_TMP_DIR} -N ${_URL}/ > ${LOGDIR}/wget.log 2>&1; _exit_code=$?
    if found_error $_exit_code ${LOGDIR}/wget.log _error_msg; then
        SCAN_ERR_MSG="$_error_msg $WGET"
        return 3
    fi

    if ! $GREP \"*\.${ARCH}\.umd\" $_TMP_DIR/index.html > $_TMP_DIR/umd.html; then
        SCAN_ERR_MSG="No_Files $GREP No umd files found in $_TMP_DIR/umd.html "
        return 4
    fi
    
    local _count_patches=`$GREP -c \"*\.${ARCH}\.umd\" $_TMP_DIR/index.html`

    write_status "$LOGDIR/active.status" "Downloading_Patches $_count_patches"
    info_log "Downloading $_count_patches UMDs from $_ipaddr in $_rpath"

    $WGET -N -F -i "$_TMP_DIR/umd.html" -P "$_TMP_DIR" -B $_URL/ > ${LOGDIR}/wget.log 2>&1; _exit_code=$?
    if found_error $_exit_code ${LOGDIR}/wget.log _error_msg; then
        SCAN_ERR_MSG="$_error_msg"
        return 5
    fi

    if ! $GREP \"*\.${ARCH}\.uxd\" $_TMP_DIR/index.html > $_TMP_DIR/uxd.html; then
        SCAN_ERR_MSG="No_Files Missing required files in specified location."
        return 6
    fi

    _count_patches=`$GREP -c \"*\.${ARCH}\.uxd\" $_TMP_DIR/index.html`
    write_status "$LOGDIR/active.status" "Downloading_Patches"
    info_log "Downloading from $_ipaddr in $_rpath <- $LINENO of $PROGNAME"

    $WGET -N -F -i "$_TMP_DIR/uxd.html" -P "$_TMP_DIR" -B $_URL/ > ${LOGDIR}/wget.log 2>&1; _exit_code=$?
    if found_error $_exit_code ${LOGDIR}/wget.log _error_msg; then
        SCAN_ERR_MSG="Download error $_exit_code"
        return 7
    fi

#### this m50r2/tux content only ######################################################################
#    if ! $GREP \"*\.${ARCH}\.uxd.sig\" $_TMP_DIR/index.html > $_TMP_DIR/sig.html; then
#        SCAN_ERR_MSG="No_Files $GREP No sig files found in $_TMP_DIR/uxd.html <- $LINENO of $PROGNAME"
#        return 8
#    fi
#
#    _count_patches=`$GREP -c \"*\.${ARCH}\.uxd.sig\" $_TMP_DIR/index.html`
#    write_status "$LOGDIR/active.status" "Downloading_Patches $_count_patches SIGs"
#    info_log "Downloading $_count_patches SIGs from $_ipaddr in $_rpath <- $LINENO of $PROGNAME"
#
#    $WGET -N -F -i "$_TMP_DIR/sig.html" -P "$_TMP_DIR" -B $_URL/ > ${LOGDIR}/wget.log 2>&1; _exit_code=$?
#    if found_error $_exit_code ${LOGDIR}/wget.log _error_msg; then
#        SCAN_ERR_MSG="$_error_msg $WGET <- $LINENO of $PROGNAME"
#        return 7
#    fi
#########################################################################################################
    return 0
}

######################
scan_ftp_location () {
    local _ipaddrr=$1
    local _usr=$2
    local _passwd=$3
    local _rpath="$4"


    validate_path $_rpath

    _PATCH_PROTO=ftp
    _URL="${_PATCH_PROTO}://${_usr}:${_passwd}@${_ipaddrr}/${_remote_path}"

    ### REVISIT THIS: ???
    #echo $_ipaddrr > $LOGDIR/ftpaddr
    _display_path=$_ipaddrr/$_rpath
    echo $_display_path > $LOGDIR/location.log

    if ! download_umds_uxds; then
        return 1
    fi

    return 0
}

#######################
scan_http_location () {
    local _ipaddrr=$1
    local _usr=$2
    local _passwd=$3
    local _rpath=$4
    local _ssl=$5

    _ssl=`echo "$_ssl" | tr '[:lower:]' '[:upper:]'`
    

    validate_path $_rpath

    if [ "X$_ssl" == "XTRUE" ]; then
        _PATCH_PROTO=https
        _URL="https://${_usr}:${_passwd}@${_ipaddrr}/${_remote_path}"
    else
        _PATCH_PROTO=http
        _URL="http://${_usr}:${_passwd}@${_ipaddrr}/${_remote_path}"
    fi

    #echo $_ipaddrr > $LOGDIR/httpaddr
    _display_path=$_httpaddr\\$_rpath
    echo $_display_path > $LOGDIR/location.log

    if ! download_umds_uxds; then
        return 1
    fi

    return 0
}

######################
scan_samba_location() {
    local _ipaddrr=$1
    local _usr=$2
    local _passwd=$3
    local _rpath=$4
    ### stop right here if server is not reachable
    local _exit_status=
    local _error_msg=

    ### domain (if any) is part of _usr, we need just user id to  user home directory, otherwise smbclient will fail
    ### _usr can be either <domain>/<user id> or <user id> _jusr_usr is same as _usr if no domain specified
    local _just_usr=`echo $_usr | sed -e 's/^[^\/][^\/]*\///'`
    #_display_path=$_ipaddrr\\$_rpath
    echo $_display_path > $LOGDIR/location.log
    echo $_ipaddrr > $LOGDIR/sambaddr

    _PATCH_PROTO=samba
    _URL="//${_ipaddrr}/${_rpath} -U ${_usr}%${_passwd}"

    if ! make_temp_dir _TMP_DIR _error_msg; then
        SCAN_ERR_MSG="Internal error in mktmp at $LINENO"
        return 2
    fi

    local _exit_code=

    pushd $_TMP_DIR >> /dev/null 2>&1

    $SMBCLIENT -E $_URL -c "prompt; mget *.uxd" > ${LOGDIR}/smbclient.log 2>&1; _exit_code=$? 
    if found_error $_exit_code ${LOGDIR}/smbclient.log _error_msg; then
        SCAN_ERR_MSG="$_error_msg in SMB at $LINENO"
        return 3
    fi

    $SMBCLIENT -E $_URL -c "prompt; mget *.umd" > ${LOGDIR}/smbclient.log 2>&1; _exit_code=$?
    if found_error $_exit_code ${LOGDIR}/smbclient.log _error_msg; then
        SCAN_ERR_MSG="$_error_msg SMB at $LINENO"
        return 4
    fi
### m50r2/tux content only #######################################################################
#    $SMBCLIENT -E $_URL -c "prompt; mget *uxd.sig" > ${LOGDIR}/smbclient.log 2>&1; _exit_code=$?
#    if found_error $_exit_code ${LOGDIR}/smbclient.log _error_msg; then
#        SCAN_ERR_MSG="$_error_msg $SMBCLIENT <- $LINENO of $PROGNAME"
#        return 4
#    fi
###################################################################################################
    popd > /dev/null 2>&1

    ### REVISITY THIS --- ???
    #$RM -f $LOGDIR/location.log
    #$RM -f $LOGDIR/sambaddr

    #echo ${_rpath} > /nn/patches/samba_profile
    popd >> /dev/null 2>&1

    return 0
}

######################
scan_usb_location () {
	local _upath=$1

    _PATCH_PROTO=usb
    validate_path $_upath
    _display_path=$_upath
    echo $_display_path > $LOGDIR/location.log
    echo $_remote_path > $LOGDIR/usb
    _URL=/mnt/usb/${_remote_path}

    if ! make_temp_dir _TMP_DIR _error_msg; then
        SCAN_ERR_MSG="$_error_msg"
        return 2
    fi

    if ! /bin/mount | /bin/grep -q -s "/dev/$USBDEV" > /dev/null 2>&1; then
        #first try auto mount filesystem
        if ! /nn/sbin/mountusb >> /dev/null 2>&1; then
		    info_warn "No usb device attached or it is already mounted --- Contunue ..."
        fi
    fi

    if [ ! -e "/mnt/usb/${_remote_path}" ]; then
        SCAN_ERR_MSG="Directory_Not_Found (/mnt/usb/${_remote_path})"
        return 1
    fi
       
    ### m50r2/tux only #### if ! $CP -f /mnt/usb/${_remote_path}/*.umd $_TMP_DIR || ! $CP -f /mnt/usb/${_remote_path}/*.uxd $_TMP_DIR || ! $CP -f /mnt/usb/${_remote_path}/*.uxd.sig $_TMP_DIR; then
    if ! $CP -f /mnt/usb/${_remote_path}/*.umd $_TMP_DIR || ! $CP -f /mnt/usb/${_remote_path}/*.uxd $_TMP_DIR; then
        SCAN_ERR_MSG="File_Not_Found $CP"
        umountusb
        return 3
    fi

    #echo /mnt/usb/${_remote_path} > /nn/patches/usb_profile
    umountusb
    return 0
}

####################
scan_EM_location() {

    local _ret_code=

    _URL=/nn/patches/tmp
    _PATCH_PROTO=em
    echo "Local System" > $LOGDIR/location.log
    #echo $_PATCH_PROTO > ${LOGDIR}/patchproto.log

    if ! make_temp_dir _TMP_DIR _error_msg; then
        SCAN_ERR_MSG="$_error_msg"
        return 2
    fi

    if ! $CP -f /nn/patches/tmp/*.umd $_TMP_DIR || ! $CP -f /nn/patches/tmp/*.uxd $_TMP_DIR; then
    ### m50r2/tux only ##  if ! $CP -f /nn/patches/tmp/*.umd $_TMP_DIR || ! $CP -f /nn/patches/tmp/*.uxd $_TMP_DIR || ! $CP -f /nn/patches/tmp/*.uxd.sig $_TMP_DIR; then
        SCAN_ERR_MSG="File_Not_Found $CP"
        return 3
    fi

    ### REVISIT THIS --- ???
    $RM -f /nn/patches/tmp/*.umd
    $RM -f /nn/patches/tmp/*.uxd
    $RM -f /nn/patches/tmp/*.uxd.sig

    return 0 
}

#. /nn/bin/crypt-softinv.sh

##################################
delete_scrambled_shreded_file () {
    local _file=$1
    if [ ! -e "$_file" ]; then
        return 1
    fi
    ### Field 5 is file length.
    local _flength=$(ls -l "$_file" | $AWK '{print $5}') || return 1

    ### Flush buffers.
    sync  > /dev/null 2>&1 || return 1
    ### Fill with random bytes.
    dd if=/dev/urandom of=$_file bs=1 count=$_flength > /dev/null 2>&1 || return 1
    ### Flush buffers again.
    sync > /dev/null 2>&1 || return 1 
    ### Fill with zeros.
    dd if=/dev/zero of=$_file bs=1 count=$_flength > /dev/null 2>&1 || return 1
    ### Flush buffers yet again.
    sync  > /dev/null 2>&1 || return 1
    # Finally, delete scrambled and shredded file.
    $RM -f $_file > /dev/null 2>&1 || return 1
    ### Flush buffers a final time.
    sync > /dev/null 2>&1 || return 1

    return 0
}

####################
get_urandom_key () {
    local _key_ref=$1

    local _tmp_file=`mktemp -q /tmp/${PROGNAME}.XXXXXX` || return 1
    ### generate file of urandom numbers, random is apperently better but it is too slow
    dd if=/dev/urandom of=${_tmp_file} bs=1 count=500 > /dev/null 2>&1 || return 1
    ### take a sumcheck of the content of this file
    local _urandom=`md5sum ${_tmp_file} | $AWK '{print $1}'` || return 1
    ### now, scramble, shred it and delete
    delete_scrambled_shreded_file ${_tmp_file}

    ### pass the urandom value back to the caller
    eval "${_key_ref}=\"${_urandom}\""

    return 0
}

############# 
hide_key () {
    local _dir=$1
    local _key=$2 

    ### not really needed here ### local _key_len=`echo $_key | wc -c`
    ### not really needed here ### _key_len=`expr $_key_len - 1`
    
    local _key=`echo "$_key" | sed -e 's/\([^ ]\)/\1:/g'`

    local _ifs_sav=$IFS
    local _tmp_file=

    local _a=0
    local _b=1
    local _d=1

    local _char=
    local _c=`expr ${_a} + ${_b}`
    _b=$_a
    _a=$_c
    _d=`expr $_d + 1`
    _c=`expr ${_a} + ${_b}`
    _b=$_a
    _a=$_c
    _d=`expr $_d + 1`

    pushd $_dir > /dev/null 2>&1 || return 1
    rm -f [0-9]*\.[0-9a-zA-Z]* > /dev/null 2>&1

    IFS=:   
    for _char in $_key; do
        touch ./${_c}.${_char} > /dev/null 2>&1
        _c=`expr ${_a} + ${_b}`
        _b=$_a
        _a=$_c
        _d=`expr $_d + 1`
    done    
    popd > /dev/null 2>&1
    IFS=$_ifs_sav

    return 0
}

############## ### a simplier version of the above ###
#hide_key () {
#    local _dir=$1
#    local _key=$2 
#
#    local _key=`echo "$_key" | sed -e 's/\([^ ]\)/\1:/g'`
#
#    local _ifs_sav=$IFS
#    local _tmp_file=
#
#    IFS=:   
#
#    local _char=
#    local _i=0
#    pushd $_dir > /dev/null 2>&1 || return 1
#    rm -f [0-9]*\.[0-9a-zA-Z]* > /dev/null 2>&1
#    for _char in $_key; do
#        let "_i += 1"
#        touch ./${_i}.${_char} > /dev/null 2>&1
#    done    
#    popd > /dev/null 2>&1
#    IFS=$_ifs_sav
#
#    return 0
#}

###############
unhide_key () {
    local _dir=$1
    local _key=$2 

    local _tmp=
    local _file=
    local _char=
    pushd $_dir > /dev/null 2>&1 || return 1
    for _file in `ls [0-9]*\.[0-9a-zA-Z]* | sort -n`; do
        _char=`echo "$_file" | sed -e 's/^[^.][^.]*\.//'`
        _tmp="${_tmp}${_char}"
        rm -f $_file > /dev/null 2>&1
    done    

    eval "${_key}=\"${_tmp}\""
    popd > /dev/null 2>&1
    return 0
}


#################
encrypt_data () {
    local _key=$1
    local _data=$2
    local _file_out=$3

    local _file_in=`mktemp -q /tmp/${PROGNAME}.XXXXXX` || return 1
    echo "$_data" > $_file_in || return 1
    if ! $GAP "$_key" $_file_in $_file_out 2 > /dev/null 2>&1; then
        ### just try it one more time, simply removing if secure delete fails for whatever reason
        if ! delete_scrambled_shreded_file ${_file_in}; then
            ### definately need to let know in the logs that faild to delete, otherwise serious 
            ### security whole, if still fails to delete, well, logs that go to EM indicated this
            $RM -f  ${_file_in}
        fi
        return 1
    fi

    ### even if success enrypting, still need to securily delete this file, so do same as above
    if ! delete_scrambled_shreded_file ${_file_in}; then
        ### definately need to let know in the logs that faild to delete, otherwise serious 
        ### security whole, if still fails to delete, well, logs that go to EM indicated this
        ### although, in this case it is just deletetion faild
        $RM -f  ${_file_in}
        return 1
    fi

    return 0
}

#################
decrypt_data () {
    local _key=$1
    local _data_ref=$2
    local _file_in=$3

    local _file_out=`mktemp -q /tmp/${PROGNAME}.XXXXXX` || return 1

    if ! $GAP "$_key" $_file_in $_file_out 1 > /dev/null 2>&1; then

        ### just try it one more time, simply removing if secure delete fails for whatever reason
        if ! delete_scrambled_shreded_file ${_file_out}; then
            ### definately need to let know in the logs that faild to delete, otherwise serious 
            ### security whole, if still fails to delete, well, logs that go to EM indicated this
            $RM -f  ${_file_out}
        fi
        return 1
    fi

    ### now, let's get the data out of file_out, basically everything in the file
    local _data_out=`cat  ${_file_out}` ### no return here, even if fails needs to del file_out later
    ### even if success enrypting, still need to securily delete this file, so do same as above
    if ! delete_scrambled_shreded_file ${_file_out}; then
        ### definately need to let know in the logs that faild to delete, otherwise serious 
        ### security whole, if still fails to delete, well, logs that go to EM indicated this
        ### although, in this case it is just deletetion faild
        $RM -f  ${_file_out}
        eval "${_data_ref}=\"\""
        return 1
    fi

    ### here we want to return 1 if data_out is empty, otherwise assign it to pass back in data
    if [ "X${_data_out}" == "X" ]; then
        return 1
    fi
     eval "${_data_ref}=\"${_data_out}\""

    return 0
}

######################
verify_signatures () {

    local _rpms=`cat $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.rpms`
    local _rpm=

    if [ -e $LOGDIR/$_patch_name-$_patch_ver.${ARCH}.usd ]; then
        pushd / > /dev/null 2>&1
        tar -xf $LOGDIR/$_patch_name-$_patch_ver.${ARCH}.usd > /dev/null 2>&1 || return 1
        popd > /dev/null 2>&1
        echo Verifying > $LOGDIR/active.status
        for _rpm in $_rpms; do
            cfsserver -signverify $LOGDIR/$_rpm $LOGDIR/$_rpm.sig  >/dev/null 2>&1 || return 1
        done
    else
        warn_alarm 2200 'Software update invalid signature or corrupt file.'
        echo "Failed_Sigs" > $LOGDIR/active.status
        return 1
    fi
    for _rpm in $_rpms; do
       rm -f $LOGDIR/$_rpm.sig
    done
    return 0
}

####################
wrong_signature () {
    local _uxd=$1
    cfsserver -signverify $_TMP_DIR/$_uxd $_TMP_DIR/$_uxd.sig  >/dev/null 2>&1 || return 0
    return 1
}

#. /nn/bin/error-softinv.sh

################
found_error () {
    local _exit_code=$1
    local _log=$2
    local _error=$3

    local _local_error=1
    local _error_string=

    ### wget and samba client does not necessarily exits with non-zero when there is some issues
    ### only obvious ones, therefore need to check a log file if there was a problem
    ### based on the content of the log file messages, a file should be overwritten
    ### every time wget or samba client is called, global loggin should be emploied outside here, 
    ### the error message passed back is actually what will go into active.status

    ### NOTE: no need for a separate handler for errors separately for wget or samba client
  
    if [ ! $_exit_code -eq 0 ]; then
        _error_str="Connection_Failed"
        _local_error=0
    fi

    ### handles wget type errors
    if grep -q '^No such directory' $_log; then
       _error_string="File_Not_Found"
       _local_error=0
    fi 
    if grep -q ' ERROR 404: Not Found. *$' $_log; then
        _error_string="File_Not_Found"
        _local_error=0
    fi
    if grep -q ' failed: Connection refused. *$' $_log; then
        _error_string="Connection_Refused"
        _local_error=0
    fi

    if grep -q ' 401 Authorization Required *$' $_log; then
        _error_string="Authorization_Failed"
        _local_error=0
    fi
    if grep -q '^Login incorrect.' $_log; then
        _error_string="Login_Incorrect"
        _local_error=0
    fi
    if grep -q ' failed: Host not found. *$' $_log; then
        _error_string="Host_Not_Found"
        _local_error=0
    fi
    if grep -q ' failed: No route' $_log; then
        _error_string="Host_Not_Found"
        #SCAN_ERR_MSG="Connect_Failed"
        SCAN_ERR_MSG="Host_Unreachable $_ipaddrr"
        _local_error=0
    fi

    ### this looks for samba type errors
    if grep -q '^session setup failed: NT_STATUS_LOGON_FAILUR' $_log; then
       _error_string="Authorization_Failed"
       _local_error=0
    fi
    if grep -q '^tree connect failed: NT_STATUS_BAD_NETWORK_NAME' $_log; then
        _error_string="Host_Not_Found"
       _local_error=0
    fi

    if grep -q '^NT_STATUS_NO_SUCH_FILE ' $_log; then
        _error_string="File_Not_Found"
       _local_error=0
    fi

    eval "$_error=\"$_error_string\""

    return $_local_error
}

###############
info_alarm () {
    local _id=$1
    local _msg=$2

    if ! write_alarm R I $_id "$_msg"; then
        return 1
    fi

    return 0
}

################
warn_alarm () {
    local _id=$1
    local _msg=$2

    if ! write_alarm R W $_id "$_msg"; then
        return 1
    fi

    return 0
}

################
error_alarm () {
    local _id=$1
    local _msg=$2

    if ! write_alarm R E $_id "$_msg"; then
        return 1
    fi

    return 0
}

#############
info_log () {
    local _msg=$1

    _msg=`$ECHO $_msg | $SED -e 's/$NL//g'`
    if ! write_alarm R I -1 "$_msg"; then
        return 1
    fi

    return 0
}

#############
warn_log () {
    local _msg=$1

    _msg=`$ECHO $_msg | $SED -e 's/$NL//g'`
    if ! write_alarm R W -1 "$_msg"; then
        return 1
    fi

    return 0
}

##############
error_log () {
    local _msg=$1

    _msg=`$ECHO $_msg | $SED -e 's/$NL//g'`
    if ! write_alarm R E -1 "$_msg"; then
        return 1
    fi

    return 0
}

################
write_alarm () {
	# Currently used alarms, see /nn/etc/DiaLoggerTaxonomy for more info
	#
	# I 2100 'Software update applied successfully'
	### write_alarm I 2100 'Software update applied successfully'
	# I 2101 'Software upgrade applied successfully'
	### write_alarm I 2101 'Software upgrade applied successfully'
	# I 2102 'Software update started'
	### write_alarm I 2102 'Software update started'
	# I 2103 'Software upgrade started'
	### write_alarm I 2103 'Software upgrade started'
	# I 2104 'Software update scheduled'
	# I 2105 'Scheduled software update completed'
	# I 2106 'Software update removed'
	### write_alarm  I 2106 'Removed software update.'
	#
	### write_alarm W 2200 'Software update invalid signature or corrupt file.
	#
	# E 2300 'Software update failed to apply'
	### write_alarm E 2300 'Software update failed to apply'
	# E 2301 'Software update failed to transfer files'
	### write_alarm E 2301 'Software update failed to transfer files'
	# E 2302 'Software upgrade failed to apply'
	### write_alarm E 2302 'Software upgrade failed to apply'
	# E 2303 'Failed to remove software update.'
	# E 2304 'Software update invalid signature or corrupt file. Retry file transfer'
	#   
	### write_alarm E 2305 'Failed to remove software update.'
    if [ ! $# -eq 4 ]; then
       return 1
    fi
    local _type=$1
    local _severity=$2
    local _alarm_id=$3
    local _alarm=$4
    # _type can be E R or N, for alarms use R for local logging use E
    # _severity must be E W or I
    # _alarm_id is a unique ID for alarm, 2000-2999 for patching, 3000-3999 for upgrades
    #       -1 value for local loggin only, no alarms are rased
    # _alarm is customer-facing alarm description
    
    if [ ! -e "$ADDNNUDIAGLOG" ]; then
       return 1
    fi

    if ! $ADDNNUDIAGLOG -mSoftwareUpdates -l$LOG_FILE -w$_type -s$_severity -v$_alarm_id "$_alarm"; then
        return 1
    fi
    
    return 0;
}

#################### not used --- need to work on this -- maybe incorporate into find_error ???
check_rpm_error () {
    local _ret=$1
    
    if [ ! $_ret -eq 0 ]; then
        return $ERROR_RPM_GEN
    fi
    
    if `grep -q 'error string goes here' $LOGDIR/rpm.log`; then
        return $ERROR_WGET_PATH
    fi
    
    return 0
}

#. /nn/bin/process-softinv.sh

################################################################################################################
### give an rpm package name, gets name, version and release out of the actual file name, since not physical ###
### rpm package is available at this time to quiery using rpm facilities themselves, checks rpm db to see    ###
### whether this particular package should be ignored, and it is in case if it is found in rpm db and it's   ### 
### version is less than or equal to one in the rpm db. MAYBE A GOOD IDEA TO HAVE METADATA IN UMD FILE       ###
### THAT REVERTS THIS BEHAVOUR TO A TRADITIONAL ONE.                                                         ###
################################################################################################################
ignore_package () {

    ### just in case if rpm package passed as location/file, sometimes good for doing testing.
    local _rpm_package=`basename $1`

    local _package_rel=`echo $_rpm_package | sed -e "s/^[^.][^.]*-[^-][^-]*-\([^-][^-]*\)\.${ARCH}\.rpm$/\1/"`
    local _package_ver=`echo $_rpm_package | sed -e "s/^[^.][^.]*-\([^-][^-]*\)-[^-][^-]*\.${ARCH}\.rpm$/\1/"`
    local _package_name=`echo $_rpm_package | sed -e "s/^\([^.][^.]*\)-[^-][^-]*-[^-][^-]*\.${ARCH}\.rpm$/\1/"`
    ### check if package_name is in rpm db, if it is, check version and release, if not, do not ignore it
    if ! $RPM -q $_package_name >> /dev/null 2>&1; then
        return 1;
    fi

    ### installed, check version, then release

    local _rpm_ver=`$RPM -q --qf %{VERSION}-%{Release} $_package_name`

      ### if rpm ver is greater than or equal to package ver then just ignore this package
      $RPMCOMP $_package_ver-$_package_rel $_rpm_ver 
      local _compare_return=$?
      if [[ $_compare_return == 1 ]]; then
         #patch version greater than installed version, do not ignore
         return 1
      elif [[ $_compare_return == -100 ]]; then 
         ### bad case, invalid parameters, mark patch as Invalid
         ### this should only be seen during testing, make sure the problem is noticed and fixed
         return 2
      fi
    ### should only get here if we want to ignore the package
    return 0

}

######################################################################################
### goes through list of packages and compares them to rpm db, ignores thouse that ###
### are either less than or equal to once found in rpm db.                         ###
######################################################################################
###########################
found_missing_packages () {

    ### this is an index file that contains packages that are available on the server
    ### normally not physically present in local file system, needs to passed as argument
    ### since varies in each scan method.
    local _index_file=$1
    ### list of rpms to be installed, this is minus ignored and missing
    local _rpms_file=$2

    shift
    shift

    ### this represents a status, which becomes invalid if at least one packages is not
    ### found in this index file, it may become invalid several times since we want to
    ### collect all packages that are misssing so that we can indicated them back to EM
    local _status=1

    ### it creates to files with .rpms and .rpm.missing extention to indicate which 
    ### rpms are missing and which should be installed in the environemtn.
    local _package
    local _package_count=$#
    local _ignored_count=0
    get_umd_tag_value $_TMP_DIR $_umd_file "SOFTWARETYPE" _umd_type
    if [ "x$_umd_type" == "xUPGRADE" ]; then
       echo $* >> $_rpms_file
       return $_status
    fi
    for _package in $*; do
        ignore_package $_package
        local _ignore=$?
        if [[ $_ignore == 0 ]]; then
            ### the package seems to be either already in rpm db and it ver/rel is either equal or less than
            ## one found in rpm db, so need to simply ignore it, my need to mark it in the warnings
            echo "$_package" >> ${_rpms_file}.ignored
            (( _ignored_count+=1 ))
            continue
        elif [ $_ignore == 2 ]; then
            _status=0
        fi
        if ! grep -q -w "$_package" $_index_file; then
           # found one package missing, but do not stop, we want to collect all of them
            echo "$_package" >> ${_rpms_file}.missing
            _status=0
        else
            echo "$_package" >> $_rpms_file
            #if [ "X${_PATCH_PROTO}" == "Xem" ]; then
            #   echo "Make sure $_package is present in the location you've indicated to EM" >> $LOGDIR/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
            #fi
        fi
    done
    if [[ $_ignored_count == $_package_count ]]; then
       ### This should mark the patch as obsolete, all packages are outdated
       _status=99
    fi

    return $_status;
}

################################################################################################################
### this essentially checks rpm packages on the server, could be remote, like http|ftp|samba|https, or local ###
### file system, like usb|em, the major goal of this procedure is to identify a list of rpms to be applied   ###
### in short, it checks the content of the patch, as opposed the patch itself, which is what build_list does ###
################################################################################################################
####################### --- ??? --- need a bit of  more work in here
check_for_packages () {
    local _umdf=$1

    local _umd_packages=
    get_umd_tag_value $_TMP_DIR $_umdf "PACKAGE" _umd_packages
    local _umd_packages1=
    get_umd_tag_value $_TMP_DIR $_umdf "PACKAGE1" _umd_packages1

    local _ret_code=0

    ### do some cleaning before processing 
    $RM -f ${LOGDIR}/${_umdf}.rpms
    $RM -f ${LOGDIR}/${_umdf}.rpms1
    $RM -f ${LOGDIR}/${_umdf}.rpms.ignored
    $RM -f ${LOGDIR}/${_umdf}.rpms1.ignored
    $RM -f ${LOGDIR}/${_umdf}.rpms.missing
    $RM -f ${LOGDIR}/${_umdf}.rpms1.missing

    ### every method has index file, but only http|https|ftp|samba really need, usb|em just have dir listing
    ### this is for uniformity mostly, instead of having different logic for every method
    local _index_file=
    local _rpms_file=${LOGDIR}/${_umdf}.rpms
    local _rpms_file1=${LOGDIR}/${_umdf}.rpms1

    case "$_PATCH_PROTO" in
        "usb") 
           if ! /nn/sbin/mountusb >> /dev/null 2>&1; then
               info_log "No usb device attached or it is already mounted"
           fi

           if /bin/mount | grep -q "/dev/$USBDEV"; then

                $RM -f ${LOGDIR}/${_umdf}.usb

                #local _usblocal
                #read _usblocal < /nn/patches/usb_profile

                ls -1 $_URL/*.rpm > $_TMP_DIR/index.usb 

                _index_file=$_TMP_DIR/index.usb

            else 
                ### problem mounting usb
                return 1
            fi
            /nn/sbin/umountusb
            ;;
        "http" | "https" | "ftp") 
            $WGET -np -P ${_TMP_DIR} -N ${_URL}/ > ${LOGDIR}/wget.log 2>&1; _ret_code=$?
            if found_error $_ret_code ${LOGDIR}/wget.log _error_msg; then
                BUILD_ERR_MSG="$_error_msg"
                return 3
            fi
            
            $RM -f ${LOGDIR}/${_umdf}.ftp

            _index_file=$_TMP_DIR/index.html
            ;;
        "samba")
            $RM -f ${LOGDIR}/${_umdf}.smb
            #local sambalocal
            #read sambalocal < /nn/patches/samba_profile

            ### The following works only in WIN SHARE/SAMBA DIR
            $SMBCLIENT -E $_URL -c "prompt;ls *.rpm" > $_TMP_DIR/index.samba 2>&1; _ret_code=$?
            if found_error $_ret_code ${_TMP_DIR}/index.samba _error_msg; then
                BUILD_ERR_MSG="$_error_msg $WGET"
                return 4
            fi

            ### This works only in LIN SAMBA DIR
            # smbclient -E $_URL -c "prompt; cd ${sambalocal}; ls *.rpm" > $_TMP_DIR/index.samba 2>&1

            _index_file=$_TMP_DIR/index.samba
            ;;
         "em")
            $RM -f ${LOGDIR}/${_umdf}.em
            #local emlocal=/nn/patches/tmp

            ### this is not true, see comments below ### ls -1 $emlocal/*.rpm > $_TMP_DIR/index.em
            _index_file=$_TMP_DIR/index.em
            echo "" > $_index_file
            ### this is to bypass EM limitation, which does not allow us to see what RPMs are actually there
            ### on my computer, as opposed to with, let's say ftp method, one can use wget to just query what files
            ### are there on the ftp server, so, in here we simply assume the files are there by dumpting list of RPMs
            ### from umd file itself into the index.em, so that, everything is trided uniformely, otherwise, need to make
            ### a special case of it, which would bring us to same thing anyway.
            local _p=
            for _p in $_umd_packages; do
                echo "$_p" >> $_index_file
            done
            ;;
    esac

    ### if go to this spot, means there was some method used to get here, which produced this index file
    ### all is needed now is go through rpms found and compare them to index file and rpm db itself
    ### so that rpm packages to be ignored and missing can be identified.
    found_missing_packages $_index_file $_rpms_file $_umd_packages
    local _found_return=$?
    #if found_missing_packages $_index_file $_rpms_file $_umd_packages; then
    if [[ $_found_return == 0 ]]; then
        eval "$2=\"Invalid\""
        ### also log it and pass it to EM
        warn_log "Missing packages in $_umd_name `cat  ${LOGDIR}/${_umdf}.rpms.missing`"
        echo "Missing packages in $_umd_name" >>$LOGDIR/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
        cat  ${LOGDIR}/${_umdf}.rpms.missing >> $LOGDIR/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
    elif  [[ $_found_return == 99 ]]; then
        eval "$2=\"Obsolete\""
        echo "Newer version of software already installed." >>$LOGDIR/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
    fi
    if [ -e "${LOGDIR}/${_umdf}.rpms.ignored" ]; then
        ### there were some packages ignore, maybe log it and just pass it on to EM
        warn_log "Ignored packages in $_umd_name `cat  ${LOGDIR}/${_umdf}.rpms.ignored`"
        #echo "Ignored packages in $_umd_name - equal or greater version already installed" >>$LOGDIR/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
        cat  ${LOGDIR}/${_umdf}.rpms.ignored >> $LOGDIR/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
    fi

    if found_missing_packages $_index_file $_rpms_file1 $_umd_packages1; then
        eval "$2=\"Invalid\""
        ### also log it and pass it to EM
        warn_log "Missing packages in $_umd_name `cat  ${LOGDIR}/${_umdf}.rpms.missing`"
        echo "Missing packages in $_umd_name" >>$LOGDIR/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
        cat  ${LOGDIR}/${_umdf}.rpms.missing >> $LOGDIR/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
    fi
    if [ -e "${LOGDIR}/${_umdf}.rpms1.ignored" ]; then
        ### there were some packages ignore, maybe log it and just pass it on to EM
        warn_log "Ignored packages in $_umd_name `cat  ${LOGDIR}/${_umdf}.rpms.ignored` <- $LINENO of $PROGNAME"
        echo "Ignored packages in $_umd_name" >>$LOGDIR/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
        cat  ${LOGDIR}/${_umdf}.rpms.ignored >> $LOGDIR/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
    fi

    ### it used to be the case when encryption happened in scan-method functions, no need, since, it is only here that we actually cache the credetials
    local _encryption_key=
    get_urandom_key _encryption_key
    local _directory="/tmp/${_umdf}"
    rm -rf $_directory
    mkdir -p $_directory > /dev/null 2>&1 || return 1
    hide_key $_directory $_encryption_key || return 1
    encrypt_data $_encryption_key "$_URL" ${LOGDIR}/${_umdf}.$_PATCH_PROTO || return 1

    cp -f ${_TMP_DIR}/${_umdf} ${LOGDIR}
    cp -f ${_TMP_DIR}/${_uxd_file} ${LOGDIR}

    return 0
}

###################
there_is_range () {
    local _req=$1
    local _sgn=$2
    local _mn=$3
    local _mx=$4
    local _nam=$5
    
    local _type=""
    local _fields=
    local _left=""
    local _right=""
    local _rel=
    local _ver=
    local _nm=
    local _tmp=
    local _ret=1

    set_left_right () {
        _left=`$ECHO "$_fields" | $SED -e 's/ [^ ][^ ]*$//'`

        _tmp="$_left"
        if $ECHO "$_left" | $GREP -q '\.'; then 
            ### all we can tell right now that either ver or rel or both are present
            ### now, let's get of rel, otherwise it is ver, but we check for it later
            _left=`$ECHO "$_left" | $SED -e 's/-[^-][^-]*$//'`
            if $ECHO "$_left" | $GREP -q '\.'; then
                ### seems  now there is also ver here, let delete it also
                _left=`$ECHO "$_left" | $SED -e 's/-[^-][^-]*$//'`
                ### we should be left with name only
            fi
        fi

        ### at point left should be just name, even if it was in the first place
        _nm="$_left"
        _left=`$ECHO "$_tmp" | $SED -e "s/^${_nm}[-]*//"`

        _right=`$ECHO "$_fields" | $SED -e 's/^[^ ][^ ]* //'`
        _left=`$ECHO "$_left" | $SED -e 's/-/\./g'`
        _right=`$ECHO "$_right" | $SED -e 's/-/\./g'`
        _ret=0
        return 0
    }

    if $ECHO "$_req" | $GREP -q '>';then
        if $ECHO "$_req" | $GREP -q '>=';then
            _type='gtoreq'
            _fields=`$ECHO "$_req" | $SED -e 's/>=/ /'`
        elif $ECHO "$_req" | $GREP -q '=>';then
            _type='gtoreq'
            _fields=`$ECHO "$_req" | $SED -e 's/=>/ /'`
        else
            _type='gt'
            _fields=`$ECHO "$_req" | $SED -e 's/>/ /'`
        fi
    elif $ECHO "$_req" | $GREP -q '<';then
        if $ECHO "$_req" | $GREP -q '<=';then
            _type='ltoreq'
            _fields=`$ECHO "$_req" | $SED -e 's/<=/ /'`
        elif $ECHO "$_req" | $GREP -q '=<';then
            _type='ltoreq'
            _fields=`$ECHO "$_req" | $SED -e 's/=</ /'`
        else
            _type='lt'
            _fields=`$ECHO "$_req" | $SED -e 's/</ /'`
        fi
    elif $ECHO "$_req" | $GREP -q '=';then
        _type='eq'
        _fields=`$ECHO "$_req" | $SED -e 's/=/ /'`
    fi

    if [ "X$_type" == "Xgtoreq" ] ||  [ "X$_type" == "Xgt" ]; then
        set_left_right
    elif [ "X$_type" == "Xltoreq" ] ||  [ "X$_type" == "Xlt" ]; then
        set_left_right
    elif [ "X$_type" == "Xeq" ]; then
        set_left_right
    else
        ### _ret is actually 1 when init, and does not change if no range, but just to make the point
        _ret=1
    fi
    eval "${_sgn}=\"${_type}\""
    eval "${_mn}=\"${_left}\""
    eval "${_mx}=\"${_right}\""
    eval "${_nam}=\"${_nm}\""

    return $_ret
}

#################################
patch_does_not_meet_requires () {

    local _require=
    local _found=0

    ### here we have to handle the following: if require is just a name and is not found in db, we are out - fail, 
    ### otherwise if require is n

    local _sign=
    local _min=
    local _max=
    local _name=
    local _rpm_n=
    local _rpm_v=
    local _rpm_r=
    local _comp_ver=

    for _require in $*; do

        if there_is_range $_require _sign _min _max _name; then
            ### we are not interested if it is not installed, later logic catches this  
            if get_rpm_tag_value $_name "NAME" _rpm_n; then
                ### if min and max are empty continue, becuase it probably something like: system-release =
                if [ "X$_min" == "X" ] && [ "X$_max" == "X" ]; then
                    continue
                fi
                ### it is in rpm db, it has ver-rel, get it
                get_rpm_tag_value $_name "VERSION" _rpm_v
                get_rpm_tag_value $_name "RELEASE" _rpm_r
                _comp_ver="${_rpm_v}.${_rpm_r}"
                if [ "X$_sign" == "Xgt" ]; then
                    if "X$_comp_ver" == "X$_min" ] || [ "X$_comp_ver" \> "X$_max" ]; then
                        continue
                    fi
                elif [ "X$_sign" == "Xgtoreq" ]; then
                    if [ "X$_comp_ver" == "X$_min" ] || [ "X$_comp_ver" \> "X$_max" ] || [ "X$_comp_ver" == "X$_max" ]; then
                        continue
                    fi
                elif [ "X$_sign" == "Xlt" ]; then
                    if [ "X$_comp_ver" \> "X$_min" ] || [ "X$_comp_ver" == "X$_min" ] && [ "X$_comp_ver" -lt "X$_max" ]; then
                        continue
                    fi
                elif [ "X$_sign" == "Xltoreq" ]; then
                    if [ "X$_comp_ver" \> "X$_min" ] || [ "X$_comp_ver" == "X$_min" ] && [ "X$_comp_ver" \< "X$_max" ] || [ "X$_comp_ver" == "X$_max" ]; then
                        continue
                    fi
                elif [ "X$_sign" == "Xeq" ]; then
                    if [ "X$_comp_ver" == "X$_min" ] || [ "X$_comp_ver" == "X$_max" ]; then
                        continue
                    fi
                fi
            fi
        else 
            ### check rpm db first, go to next upon success, otherwise check if has been scheduled to get there
            if $RPM -q $_require > /dev/null 2>&1; then
                continue
            fi
        fi

        ### ??? see if has been scheduled: this needs to be really thought through, since if has been scheduled may show patch as avalable, however it is really only for scheduling 
        ### purposes, although the user see it as being avalable and might try to apply it, where it would fail by rpm since the dependency is nor really in rpm db
        if [ -e "${LOGDIR}/${_require}.${ARCH}.umd.scd" ]; then
            continue
        fi

        ### the above rules are not satisfied, the package becomes invalid, by default it is always available
        _found=1
        info_log "WARNING: Please apply the ${_require} update prior to installing the ${_umd_name} update"
        $ECHO "WARNING: Please apply the ${_require} update prior to installing the ${_umd_name} update" >> $LOGDIR/readme/Warnings-${_umd_name}-${_umd_ver}-${_umd_rel}.txt
    done

    if [ $_found -eq 1 ]; then
        return 0
    else
        return 1
    fi
}

#################
find_patches () {
    local _dir=$1

    $LS ${_dir}/*.umd > /dev/null 2>&1 || return 1
    $LS  ${_dir}/*.uxd > /dev/null 2>&1 || return 1
    #$LS  ${_dir}/*.uxd.sig > /dev/null 2>&1 || return 1

    return 0
}

##############
build_list() {

    local _umd_file=
    $RM -f $PATCH_CACHE

    local _ret_code=

    ### NOW: this building status should be updated with % as each umd file is processed, could be count each umd out of totatl umds
    write_status "$LOGDIR/active.status" "Building "
    info_log "Building ... "

    pushd $_TMP_DIR >> /dev/null 2>&1

    # no need to go ahead if there are no *.umd AND *.uxd files in temp dir  
    if ! find_patches $_TMP_DIR; then
        BUILD_ERR_MSG="No_Files Could not find any patches (*.umd, *.uxd, *.uxd.sig files) in $_TMP_DIR"
        return 1
    fi

    local _requires_list=
    local _rpm_ret=

    local _internal_status=

    ### it is guaranteed `ls -1 *.umd` exists
    for _umd_file in `$LS -1 *.umd`; do
        local _status=""
        local _umd_name=

        if ! get_umd_tag_value $_TMP_DIR $_umd_file "TITLE" _umd_name; then
            ### need to login this fact into worning/logs, etc. --- ????
            info_log "Ignoring ${_umd_file} --- ${_umd_name} ... <- $LINENO of $PROGNAME"
            continue
        fi

        # if you get this far you are guaranteed that ver and rel has some values
        local _umd_ver
        if ! get_umd_tag_value $_TMP_DIR $_umd_file "VERSION" _umd_ver; then
            ### this is more or less for completeness, since if can query the name of package from rpm db and fail to query
            ### its version is when something really goes wrong, e.g. db gets deleted right after it has been queried, 
            ### no point of going on like that
            BUILD_ERR_MSG="DB_Error Could not query get VERSION tag from  $_umd_file in  $_TMP_DIR directory"
            return 2
        fi
        local _umd_rel
        if ! get_umd_tag_value $_TMP_DIR $_umd_file "RELEASE" _umd_rel; then
            BUILD_ERR_MSG="DB_Error Could not query get RELEASE tag from  $_umd_file in  $_TMP_DIR directory"
        fi

        ### NEED TO DECIDE HOW TO TREAT READMEs and WARNINGs files - ???


        ### warnings file is updated requires check function to show what has been misssing if anything
	    $RM -f $LOGDIR/readme/Warnings-${_umd_name}-${_umd_ver}-${_umd_rel}.txt
	    $TOUCH $LOGDIR/readme/Warnings-${_umd_name}-${_umd_ver}-${_umd_rel}.txt
        
        ### at least one uxd file guaranteed, however need to check whether the correct one exists
        local _uxd_file="$_umd_name-$_umd_ver-$_umd_rel.${ARCH}.uxd"
        ### in case if does not exist need to continue next umd, however need to note in warnings or logs etc ???
        if [ ! -e "$_uxd_file" ]; then
            info_log "Missing upgrade description file $_uxd_file for $_umd_file in $_TMP_DIR, continuing to build list"
            info_log "`$LS -al $_TMP_DIR`"
            continue;
        fi

        ### check if requires is present, if it does then check if the patch matches it agains the system, and if not then only make it ivalid
        if get_umd_tag_value $_TMP_DIR $_umd_file "REQUIRES" _requires_list; then
            ### need to handle this system-release specified in the patch relative to the one on the system, see more comments inside function, i
            ### note, requires does not have to contain only system-release package, could be more, also, we can handle all this in the Requires field 
            ### of the wrapper, the idea is to have these requires relate to other patches, system-release, upgrades, the requires inside wrapper (uxd file)
            ### really just ties together itself with its content and maybe other patches but via its content (rpms) not the other wrappers, which what this
            ### requires in umd file is for, this feature is not utilized much, but it carried here from the original design and can be used but what for ???.
            if patch_does_not_meet_requires $_requires_list; then
                _internal_status="Invalid"
            fi
        fi
        ### else there was no requies for this package --- need to revisit this logic, at least something. --- ???, otherwise applies everywhere

        ### m50r2/tux only ########################################################################################################
        #if [ ! -e "${_uxd_file}.sig" ] || wrong_signature ${_uxd_file}; then
        #    info_log "Missing signature or corrupted $_uxd_file file for $_umd_file in $_TMP_DIR, ingoring"
        #    _internal_status="Invalid"
        #fi
        ###########################################################################################################################

        local _rpm_name
        if ! get_rpm_tag_value $_umd_name "NAME" _rpm_name; then
            # if non-zero (2) returned means package is not installed
            # otherwise rpm name/ver/rel are garanteed to be non-empty
            # means not installed, Available, all Available should be check for 
            # availability of corresponding RPMs, if not found status goes to Partial

            # when returns 1, wrong parameters, do we really need this ???

            # assume available, gets overwritten in check for packages if not all packages are found
            _status="Available"
            if ! check_for_packages $_umd_file _status; then
                info_log "$BUILD_ERR_MSG "
                _status="Invalid" ### though status maybe set in check for packages
            fi
        else
            local _rpm_ver
            get_rpm_tag_value $_rpm_name "VERSION" _rpm_ver
            # if umd ver/rel is greater than rpm ver/rel means Available
            if [ $_umd_ver \> $_rpm_ver ]; then
                _status="Available"
                if ! check_for_packages $_umd_file _status; then
                    info_log "$BUILD_ERR_MSG <- $LINENO of $PROGNAME"
                    _status="Invalid" ### though status maybe set in check for packages
                fi
            elif [ $_umd_ver == $_rpm_ver ]; then
                # same, need to check for umd rel and rpm rel
                local _rpm_rel
                get_rpm_tag_value $_rpm_name "RELEASE" _rpm_rel
                if [ $_umd_rel \> $_rpm_rel ]; then
                    _status="Available"
                    if ! check_for_packages $_umd_file _status; then
                        info_log "$BUILD_ERR_MSG <- $LINENO of $PROGNAME"
                        _status="Invalid" ### though status maybe set in check for packages
                    fi
                elif [ $_umd_rel == $_rpm_rel ]; then
                    # if umd rel is equal to rpm rel manes Applied
                    _status="Applied"
                else
                    # means Obsolete
                    _status="Obsolete"
                fi
            else 
                # otherwise Obsolete, umd ver/rel is less than rpm ver/rel
                _status="Obsolete"
            fi
        fi
        
        # output format (fields separated by tabs): 
        #       Name, Version, ShortDescription, RebootReqired, Size, Status
        local _umd_reboot=
        local _umd_warnings=
        get_umd_tag_value $_TMP_DIR $_umd_file "DESCRIPTION" _umd_desc
        get_umd_tag_value $_TMP_DIR $_umd_file "REBOOT" _umd_reboot
        get_umd_tag_value $_TMP_DIR $_umd_file "SIZE" _umd_size
        get_umd_tag_value $_TMP_DIR $_umd_file "SOFTWARETYPE" _umd_type
        get_umd_tag_value $_TMP_DIR $_umd_file "WARNINGS" _umd_warnings
        if [ -n "$_umd_warnings" ]; then
           echo $_umd_warnings >>$LOGDIR/readme/$_umd_name-$_umd_ver-$_umd_rel.warning
        fi
        local _str_size=$_umd_size

	    local _key_code
        if get_umd_tag_value $_TMP_DIR $_umd_file "KEYCODE" _key_code; then
        	/nn/bin/cfsgetcode $_key_code
        	_code_value=$?
                if [ $_code_value -le 0 ]; then
                        erro_log "No Proper keycode applied. Please retrieve and apply a feature keycode prior to patching the system."
                        echo "No Proper keycode applied. Please retrieve and apply a feature keycode prior to patching the system." >>$LOGDIR/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
                        _internal_status="Invalid"
                fi
        fi


        ### indiecated patch has been scheduled, should be removed when applied
        if [ -e ${LOGDIR}/${_umd_file}.scd ]; then
            _status="Schedule"
        fi
        ### this is to mark that patch has once change its status to obsolete, 
        ### meaning was upgraded, this stops from rolling this patch back more
        ### than once, otherwise rpm behaves unpredictably, rpm limitations
        if [ $_status == "Obsolete" ]; then
            touch ${LOGDIR}/${_umd_file}.obs
             _patch_name=$_umd_name
             local line
             while read line
             do
                _patch_ver="${_umd_ver}-${_umd_rel}"
                echo $line | grep -w $_patch_name | grep -w $_patch_ver | grep -w Removable >/dev/null 2>&1
                ret_code=$?
                if [ $ret_code -eq 0 ]; then
                   line=${line/        Removable/      NotRemovable}
                   echo "$line" >> /nn/patches/info/history.tmp
                 else
                   echo "$line" >> /nn/patches/info/history.tmp
                fi
              done <$PATCH_HISTORY
              rm -f $PATCH_HISTORY
              mv /nn/patches/info/history.tmp $PATCH_HISTORY
        fi

        #_umd_reboot="reboot"
        #Avaliable: Name, Version, ShortDescription, RebootReqired, Size, Status
        if [ "$_internal_status" == "Invalid" ] && [ ! "$_status" == "Applied" ]; then
           _status="Invalid"
          _internal_status=
        fi
       
        if [ $_status == "Available" ]; then
            touch ${LOGDIR}/${_umd_file}.ava
            if [ -f /nn/patches/info/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt ]; then
                ### here do something with the wornings, need to get where EM can see it
                #cat  /nn/patches/info/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
               echo "" >> /nn/patches/info/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
               #rm -f /nn/patches/info/readme/Warnings-$_umd_name-$_umd_ver-$_umd_rel.txt
            fi
        fi

        if [ $_status == "Available" ]; then
            rpm2cpio $_uxd_file | cpio -i -d > /dev/null 2>&1
            $CP -f nn/patches/sigs/*.usd $LOGDIR > /dev/null 2>&1
            $CP -f nn/patches/info/readme/* $LOGDIR/readme > /dev/null 2>&1
            if [ -e "nn/patches/info/${_umd_name}-${_umd_ver}-${_umd_rel}/pre_patch.sh" ]; then
                if [ ! -e "${LOGDIR}/${_umd_name}-${_umd_ver}-${_umd_rel}.pre_patch.done" ]; then
                    info_log "Found PRE script for ${_umd_name}-${_umd_ver}-${_umd_rel} "
                    if ! bash -x nn/patches/info/${_umd_name}-${_umd_ver}-${_umd_rel}/pre_patch.sh > ${LOGDIR}/${_umd_name}-${_umd_ver}-${_umd_rel}.pre_patch.log 2>&1; then
                        info_log "Found PRE script FAILED TO EXECUTE for ${_umd_name}-${_umd_ver}-${_umd_rel} <- $LINENO of $PROGNAME"
                    else
                        touch ${LOGDIR}/${_umd_name}-${_umd_ver}-${_umd_rel}.pre_patch.done
                    fi
                else
                    local _umd_clean=
                    get_umd_tag_value $_TMP_DIR $_umd_file "CLEAN" _umd_clean
                    _umd_clean=`echo $_umd_clean | tr 'A-Z' 'a-z'`
                    if [ "X$_umd_clean" == "Xyes" ]; then
                        info_log "PRE script for ${_umd_name}-${_umd_ver}-${_umd_rel} has already been executed <- $LINENO of $PROGNAME"
                        if ! bash -x nn/patches/info/${_umd_name}-${_umd_ver}-${_umd_rel}/pre_patch.sh > ${LOGDIR}/${_umd_name}-${_umd_ver}-${_umd_rel}.pre_patch.log 2>&1; then
                            info_log "PRE script FAILED TO EXECUTE for ${_umd_name}-${_umd_ver}-${_umd_rel} <- $LINENO of $PROGNAME"
                        else
                            rm -f ${LOGDIR}/${_umd_name}-${_umd_ver}-${_umd_rel}.pre_patch.done
                            touch ${LOGDIR}/${_umd_name}-${_umd_ver}-${_umd_rel}.pre_patch.done
                        fi
                    fi
                fi
            fi
        fi
 
        info_log "$_umd_name $_umd_ver $_umd_rel $_umd_desc $_str_size $_umd_reboot $_status <- $LINENO of $PROGNAME"
        printf "%s\t%s-%s\t%s\t%s\t%s\t%s\n" "$_umd_name" "$_umd_ver" "$_umd_rel" "$_umd_desc" "$_str_size" "$_umd_reboot" "$_status"
        printf "%s\t%s-%s\t%s\t%s\t%s\t%s\n" "$_umd_name" "$_umd_ver" "$_umd_rel" "$_umd_desc" "$_str_size" "$_umd_reboot" "$_status" >> $PATCH_CACHE

        ### this is to mark what method which patch used to get here, previously a global patchproto.log
        ### was used, however statelessness of softinv will override this when we're in context of 
        ### scheduling patches.
 
        echo "${_PATCH_PROTO}" > ${LOGDIR}/${_umd_file}.log

    done
    popd >> /dev/null 2>&1

    return 0
}

#. /nn/bin/tags-softinv.sh


######################
get_umd_tag_value () {
    # a generic function to query an xml file value of a tag
    # USAGE:get_umd_tag_value <LOCATION DIRECTORY PATH> <XML FILE NAME> <TAG NAME> <VAR NAME TO PASS BACK VALUE>
    # multiple values are passed back as space separated, although xml utility outputs them one per line

    local _path=$1
    local _xml_file=$2
    local _tag=$3

    local _value_list=
    local _tagvalue=

    if [ ! $# -eq 4 ]; then
        return 1
    fi

    if [ ! -e "${_path}/${_xml_file}" ]; then
        return 2;
    fi

    _tag=`echo "$_tag" | tr '[:lower:]' '[:upper:]'`

    local _savIFS=$IFS
    IFS=$'\n'

    for _tagvalue in `/opt/bin/get-xml-tag-values ${_path}/${_xml_file} $_tag`; do
        if [ "X$_tag" == "XREQUIRES" ]; then
            _tagvalue=`echo $_tagvalue | sed -e 's/  *//g'`
        fi

        if [ -n "$_value_list" ]; then
        	_value_list="$_value_list $_tagvalue"
        else
            _value_list="$_tagvalue"
        fi
    done
    IFS=$_savIFS

    if [ "X$_value_list" == "X" ]; then
        return 3;
    fi

    eval "$4=\"$_value_list\""

    return 0;
}


##########################
get_package_tag_value () {
    # a generic function to query an rpm package for a value of a tag
    # an rpm package is a physical file as opposed to one in rpm db
    # USAGE:get_package_tag_value <LOCATION PATH> <RPM PACKAGE FILE NAME> 
    #                     <TAG NAME> <VAR NAME TO PASS BACK VALUE>
    local _path=$1
    local _package=$2
    local _tag=$3

    if [ ! $4 ]; then
        if [ $DEBUG ] && [ $DEBUG == "TRUE" ]; then
            echo "ERROR: missing pass-back parameter in get_package_tag_value(...)"
            echo "$1, $2, $3, $4"
        fi
        return 3
    fi

    if [ ! -e "${_path}/${_package}" ]; then
        if [ $DEBUG ] && [ $DEBUG == "TRUE" ]; then
            echo "ERROR: Did not find $_package in $_path"
        fi
        return 2;
    fi

    local _value
    _value=`$RPM_BIN -qp --qf "%{${_tag}}" ${_path}/${_package}`
    if [ ! "$?" -eq 0 ]; then
       local _error_test=`echo $_value | sed -e 's/^ *\(error:\)  *.* *$/\1/'`
       if [ "$_value" == "(none)" ] || [ "$_error_test" == "error:" ]; then
         eval "$4=\"\""
       fi
       return 1;
    fi
    eval "$4=\"$_value\""
    return 0;
}

######################
get_uxd_tag_value () {
    get_package_tag_value $*
    return $?
}


######################
get_rpm_tag_value () {
    # a generic function to query an rpm package for a value of a tag
    # an rpm package is in rpm db
    # USAGE:get_rpm_tag_value <RPM PACKAGE NAME> <TAG NAME> <VAR NAME TO PASS BACK VALUE>

    local _package=$1
    local _tag=$2

    if [ ! $# -eq 3 ]; then
        return 1
    fi

    local _value
    local _ret

    _value=`$RPM -q --qf "%{${_tag}}" ${_package}`; _ret=$?

    ### in most cases value is going to be: 'package package-aa is not installed' if package-aa is not installed
    if [ ! "$_ret" -eq 0 ]; then
       local _error_test=`echo $_value | sed -e 's/^ *\(error:\)  *.* *$/\1/'`
       if [ "X$_value" == "X(none)" ] || [ "X$_error_test" == "Xerror:" ]; then
           eval "$3=\"\""
       fi

       _error_test=`echo $_value | sed -e 's/^ *package  *[^ ][^ ]*  *\(is not installed\) *$/\1/'`
       if [ "X$_error_test" == "Xis not installed" ]; then
           eval "$3=\"\""
       fi

       return 2
    fi
    eval "$3=\"$_value\""

    return 0;
}

##############################################################

########### this one to do some clean up on exit, either zero or non-zero exit, recognizes DEBUG is FALSE --- do nothing just exit 0
cleanup() {
########### no need to return non-zero exit anymore, or if does this will trap it and will exit zero anyway
    ### delete temporary directory and files
    if [ "X$DEBUG" == "XFALSE" ]; then
        $RM -f $LOGDIR/*.log
        $RM -rf $_TMP_DIR
        $RM -f $LOGDIR/*.rpm
        $RM -f $LOGDIR/*.sig
    fi
    exit 0
}
#trap cleanup EXIT  ## Set trap to call cleanup on exit


    
####################
set_in_progress(){
    echo Working > $LOGDIR/active.status
}

####################
validate_path () {
    # call this to perform any special formatting for paths passed in
    _remote_path=$1
    #strip leading slashes from path
    _remote_path=${_remote_path##/}
    _remote_path=${_remote_path##\\}
    #replace any // with / and \ with /
    _remote_path=${_remote_path//\/\//\/}
    _remote_path=${_remote_path//\\\\//}
}

###################
download_patch () {
    local _patch_name=$1
    local _patch_ver=$2
    local _download_ret=
    optional_selects=

    if [ $# -gt 2 ]; then
       shift; shift
       optional_selects=$*
       if [ `echo $optional_selects | grep *.rpm` ]; then
          echo $optional_selects >> ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.rpms
       fi
    fi

    if [ ! "$_patch_name" ] || [ ! "$_patch_ver" ]; then
        return 1
    fi

    get_umd_tag_value $LOGDIR $_patch_name-$_patch_ver.${ARCH}.umd "SIZE" _umd_size || return 1
    get_umd_tag_value $LOGDIR $_patch_name-$_patch_ver.${ARCH}.umd "SOFTWARETYPE" _umd_type || return 1

    local _flags=totalsize startsize upgrading
    local _flag=
    
    for _flag in $_flags; do
        if [ -e $LOGDIR/$_flag ]; then
            $RM -f $LOGDIR/$_flag
        fi
    done

    if [ "x$_umd_type" == "xUPGRADE" ]; then
        touch $LOGDIR/upgrading
        if echo $_umd_size | grep MB >/dev/null 2>&1 ; then
            _total_size=`expr match "$_umd_size" '\([0-9]*\)'`
            echo $_total_size >$LOGDIR/totalsize
        fi
        _starting_size=`du -mSs $LOGDIR`
        for _start_size in $_starting_size; do
            echo $_start_size >$LOGDIR/startsize
            break
        done    
    fi

    if [ ! -h /var/spool/repackage ] && [ ! -d /var/spool/repackage ]; then
        mkdir /var/spool/repackage
    fi

    write_status "$LOGDIR/active.status" "Downloading"
    info_log "Downloadind "

    ### OUTSTANDING: make sure to exit with appropriate ERROR when this file is not found
    
    local _patch_proto=
    local _patch_size=

    if [ -e $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.log ]; then
        read _patch_proto _patch_size< $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.log
    else
        return 3
    fi

    local _str_tmn
    if [ -e $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.ava ] || [ -e $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.scd ]; then
        $RM -f ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.trn
        
        echo -n " ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.uxd" >> ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.trn
        
        _str_tmn=`date '+%a %b %d %H:%M:%S %Y'`
        printf "%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_str_tmn" "$_patch_proto" "Downloading" > ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.str
        local _url=
        local _decryption_key=
        local _directory="/tmp/${_patch_name}-${_patch_ver}.${ARCH}.umd"
        local _tmp_key
        if ! unhide_key $_directory _tmp_key; then
            DWNLD_ERR_MSG="Failed_Key "
            clean_temp ${_patch_name}-${_patch_ver}
            return 1  
        fi
        rm -rf $_directory > /dev/null 2>&1
        _decryption_key=$_tmp_key
        ### decrypt url
        if ! decrypt_data $_decryption_key _url $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.$_patch_proto; then
            DWNLD_ERR_MSG="Failed_Decrypt "
            return 1
        fi

        if ! download_patch_proto $_patch_name-$_patch_ver "$_url" $_patch_proto; then
            if [ "X$DWNLD_ERR_MSG" == "X" ]; then
                DWNLD_ERR_MSG="Download_Failed "
            fi
           clean_temp ${_patch_name}-${_patch_ver}
           return 1
        fi 

        write_status "$LOGDIR/active.status" "Verifying_Signatures"
        info_log "Verifying_Signatures "
        if ! verify_signatures; then
            DWNLD_ERR_MSG="Failed_Sigs "
            clean_temp ${_patch_name}-${_patch_ver}
            return 1
        fi
        
        echo "" >> ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.trn
        
        _str_tmn=`date '+%a %b %d %H:%M:%S %Y'`
        printf "%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_str_tmn" "$_patch_proto" "Downloaded" > ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.str

    else
        return 1
    fi
    return 0
}

########################
download_patch_proto() {
    local _patch_id=$1
    local _url=$2
    local _patch_proto=$3

    local _rpms=`cat $LOGDIR/$_patch_id.${ARCH}.umd.rpms`

    local _trn=trn
    local _ret_code
    local _rpm

    for _rpm in $_rpms; do 
        case "$_patch_proto" in
            "http" | "https" | "ftp" ) 
                $WGET -np -P ${LOGDIR} -N ${_url}/${_rpm} > ${LOGDIR}/wget.log 2>&1; _ret_code=$?
                if found_error $_ret_code ${LOGDIR}/wget.log _error_msg; then
                    DWNLD_ERR_MSG="$_error_msg"
                    error_alarm 2301 "Software update failed to transfer files, rc=$_ret_code"
                    return 3
                fi
                echo -n " ${LOGDIR}/$_rpm" >> ${LOGDIR}/$_patch_id.${ARCH}.umd.$_trn
                ;;
            "samba") 
                pushd $LOGDIR >> /dev/null 2>&1
                #local sambalocal
                #read sambalocal < /nn/patches/samba_profile
                ### why 'cd ${smblocal}' appreently this causes problem because, we're already in smblocal <- from url
                ### MORE COMMENTS: this is how linux samba works
                ### $SMBCLIENT $_url -c "prompt;cd ${sambalocal}; mget $_rpm"  > $LOGDIR/smbclient.log 2>&1; _ret_code=$?
                $SMBCLIENT -E $_url -c "prompt; mget $_rpm" > ${LOGDIR}/smbclient.log 2>&1; _ret_code=$?
                if found_error $_ret_code ${LOGDIR}/smbclient.log _error_msg; then
                    DWNLD_ERR_MSG="$_error_msg "
                    error_alarm 2301 "Software update failed to transfer files, rc=$_ret_code"
                    return 7
                fi
                ### this should not be here since exposes userid/password
                ### echo "smbclient $_url -c \"prompt;cd ${sambalocal}; mget $_rpm\""  >> $LOGDIR/smb.log
                echo -n " ${LOGDIR}/$_rpm" >> ${LOGDIR}/$_patch_id.${ARCH}.umd.$_trn
                ;;
           "usb") 
                if ! /nn/sbin/mountusb >> /dev/null 2>&1; then
                    info_log "No usb device attached or it is already mounted --- Contunue ..."
                fi

                if /bin/mount | grep -q "/dev/$USBDEV"; then
                    if ! $NICE --adjustment=5 $CP -a -f $_url/$_rpm $LOGDIR > /dev/null 2>&1; then
                        ### maybe some info needs to be put intot warnings in readme ###  2>>$LOGDIR/readme/Warnings-$_patch_id.txt; then
                        DWNLD_ERR_MSG="Download_Failed $CP $_rpm "
                        error_alarm 2301 "Software update failed to transfer files"
                        return 3
                    fi
                    echo -n " $LOGDIR/$_rpm" >> ${LOGDIR}/$_patch_id.${ARCH}.umd.$_trn
                else
                    DWNLD_ERR_MSG="Download_Failed $CP $_rpm "
                    error_alarm 2301 'Software update failed to transfer files'
                    return 3
                fi
                ;;
            "em")
                if ! mv -f $_url/$_rpm $LOGDIR > /dev/null 2>&1; then
                    DWNLD_ERR_MSG="Download_Failed mv $_rpm "
                    error_alarm 2301 'Software update failed to transfer files'
                    return 3
                fi
                echo -n " ${LOGDIR}/$_rpm" >> ${LOGDIR}/$_patch_id.${ARCH}.umd.$_trn
                ;;
        esac
    done
    if [ -e ${LOGDIR}/wget_$_patch_id.log ]; then
       $RM -f ${LOGDIR}/wget_$_patch_id.log 
    fi
    if [ $_patch_proto == usb ]; then
       /nn/sbin/umountusb
    fi
}

################
clean_temp () {
        $RM -f /nn/patches/blocking_flag
        $RM -f ${LOGDIR}/$1.${ARCH}.umd.trn
        $RM -f ${LOGDIR}/$1.${ARCH}.umd.str
}


################
apply_patch () {
    local _patch_name=$1
    local _patch_ver=$2

    local _force=

    if [ ! "$_patch_name" ] || [ ! "$_patch_ver" ]; then
        return 1
    fi

    local _requires_list
    local _requires

    ### before doing anything we need to check whether we're not applying something that has one or more items in its requires list scheduled 
    get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "REQUIRES" _requires_list

    ### if at least one item in the list found to be scheduled then apply can not go on, unfortunately only return error code is informative here
    for _requires in $_requires_list; do
        if [ -e "${LOGDIR}/${_requires}.${ARCH}.umd.scd" ]; then
            ### only need to find one item scheduled, can probably return directly from here, probably need some sort of  WARNING
            echo "Apply_Failed" > $LOGDIR/active.status
            return 2
        fi
    done

    if [ -e /nn/patches/blocking_flag ]; then
        echo "Apply_Failed" > $LOGDIR/active.status
        return 3
    else
        touch /nn/patches/blocking_flag
    fi

    local _trn
    local _umd_desc
    local _umd_reboot
    local _umd_rollback
    local _umd_force
    local _umd_type

    read _trn < $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.trn
    #get_package_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.uxd "PROBLEMDESCRIPTION" _umd_desc
    get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "DESCRIPTION" _umd_desc
    get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "REBOOT" _umd_reboot
    get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "ALLOWROLLBACK" _umd_rollback
    get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "DEPENDENCYCHECK" _umd_force
    get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "SOFTWARETYPE" _umd_type
    _umd_force=`echo $_umd_force | tr 'A-Z' 'a-z'`
    if [ "$_umd_force" == no ]; then
        _force="--force"
    fi
    
    _umd_reboot=`echo $_umd_reboot | tr 'A-Z' 'a-z'`
    _umd_rollback=`echo $_umd_rollback | tr 'A-Z' 'a-z'`
    local _td=`date '+%a %b %d %H:%M:%S %Y'`
    # note that this should return value of wc and not return code
    local _istopped=`processcontrol detaillist | grep Stopped | wc -l`
    printf "%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_td" "$_patch_proto" "Applying" > $LOGDIR/$_patch_name-$_patch_ver.${ARCH}.umd.str
    echo Applying > $LOGDIR/active.status
    echo $_patch_name-$_patch_ver > $LOGDIR/active

    if [ "$_umd_type" == UPGRADE ]; then
       `/nn/bin/processcontrol stop psm & >/dev/null 2>&1`
       `/nn/bin/processcontrol stop Msm & >/dev/null 2>&1`
       `/etc/init.d/MonitGaurd stop & >/dev/null 2>&1`
       `/nn/bin/processcontrol stop monit & >/dev/null 2>&1`
       #`/nn/bin/processcontrol stop MonitGaurd &>/dev/nul 2>&1`
    fi
    
    if [ ! "$_umd_type" == UPGRADE ]; then
       info_alarm 2102 'Software update started'
    else
       info_alarm 2103 'Software upgrade started'
    fi

    if [ -e $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.pre ]; then
       cfsserver -signverify $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.pre $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.sig
       _pre_keycode_check=$?
       if [ ! $_pre_keycode_check -eq 0 ]; then
          error_alarm 2300 'Software update failed to apply'
          return 4
       fi
       /bin/bash -x $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.pre >> $PATCH_LOG 2>&1
       _pre_apply_ret=$?
       if [ ! $_pre_apply_ret -eq 0 ]; then
          error_alarm 2300 'Software update failed to apply'
          return 4
       fi
    fi

    local _rpm_ret=0
    local _save_rpm_ret=0
    if [ "$_umd_rollback" == "no" ]; then
       $RPM --define '_binary_payload w1.gzdio' $_force -Uvvh ${_trn} >>$PATCH_LOG 2>&1
       _rpm_ret=$?
       save_rpm_if_good;
       _save_rpm_ret=$?
    else
       $RPM --define '_binary_payload w1.gzdio' --define '_rollback_transaction_on_failure 1' --define '_unsafe_rollbacks 1059710400' --define '_repackage_all_erasures 1' $_force -Uvvh ${_trn}  >>$PATCH_LOG 2>&1
       _rpm_ret=$?
       save_rpm_if_good;
       _save_rpm_ret=$?
    fi
    if (( $_rpm_ret != 0 )) || (( $_save_rpm_ret != 0)); then
        clean_temp $_patch_name-$_patch_ver
        echo Apply_Failed > $LOGDIR/active.status
        if [ ! "$_umd_type" == UPGRADE ]; then
            error_alarm 2302 "Software upgrade failed to apply, rpm retcode $_rpm_ret"
        else
            error_alarm 2300 "Software update failed to apply, rpm retcode $_rpm_ret"
        fi
        return 4
    fi

    if [ -s $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.trn1 ]; then
        read _trn < $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.trn1
        $RPM_BIN --define '_binary_payload w1.gzdio' $_force -Uvvh ${_trn} >>$LOGDIR/$_patch_name-$_patch_ver.log 2>&1
        _rpm_ret=$?
        save_rpm_if_good;
        _save_rpm_ret=$?
        if (( $_rpm_ret != 0 )) || (( $_save_rpm_ret != 0)); then
           clean_temp $_patch_name-$_patch_ver
           echo Apply_Failed > $LOGDIR/active.status
           if [ ! "$_umd_type" == UPGRADE ]; then
              error_alarm 2302 "Software upgrade failed to apply, rpm retcode $_rpm_ret"
           else
              error_alarm 2300 "Software update failed to apply, rpm retcode $_rpm_ret"
           fi
           return 4
        fi
     fi 


    _td=`date '+%a %b %d %H:%M:%S %Y'`
    # TOO EARLY:    echo Apply_Success > $LOGDIR/active.status
    #History: Name, Version, ShortDescription, Category, AppliedDate, Removable
    if [ "$_umd_rollback" = "no" ] || [ -e ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.obs ]; then
        printf "%s\t%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_umd_desc" "Patch Applied" "$_td" "NotRemovable" >> $PATCH_HISTORY
    else
        printf "%s\t%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_umd_desc" "Patch Applied" "$_td" "Removable" >> $PATCH_HISTORY
    fi

    if [ ! "$_umd_type" == UPGRADE ]; then
       info_alarm 2100 'Software update applied successfully'
    else
       info_alarm 2101 'Software upgrade applied successfully'
    fi

    local _patch_proto
    local _patch_size
    if [ -e $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.log ]; then
        read _patch_proto _patch_size < $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.log
    else
        return 1
    fi

    printf "%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_td" "$_patch_proto" "Applied" > ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.str
    printf "%s" "$_patch_name" > $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.end
    printf "%s" " $_patch_ver" >> $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.end
    printf "%s" " $_td" >> $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.end
    echo "" >> $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.end
    read _rpms < $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.trn
    for _file in $_rpms; do
      if [ -e $LOGDIR/$_file ]; then
         $RM -f $LOGDIR/$_file
         $RM -f $LOGDIR/$_file.sig 
         $RM -f $LOGDIR/${_patch_name}-${_patch_ver}.*
      fi
    done
    if [ -s $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.trn1 ]; then
       read _rpms < $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.trn
       for _file in $_rpms; do
          if [ -e $LOGDIR/$_file ]; then
             $RM -f $LOGDIR/$_file
             $RM -f $LOGDIR/$_file.sig
          fi
       done
    fi    
    $RM -f /nn/patches/blocking_flag
    $RM -f ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.ava
    $RM -f ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.str
    #$RM -f ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.trn*
    #$RM -f ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.rpm*
    $RM -f $LOGDIR/active


    if [ -e "${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.scd" ]; then
        FROM_APPLY=TRUE
        modify_schedule $_patch_name $_patch_ver
        $RM -f ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.scd
    fi


    touch ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.app

    #$RM -f ${LOGDIR}/${_patch_name}-${_patch_ver}.*
    #if [ -e /nn/bin/change_perm ]; then
    #    pushd .
    #    cd /
    #    chmod 0777 /nn/bin/change_perm
    #    /bin/bash /nn/bin/change_perm / > /dev/null 2>&1 
    #    popd
    #fi
    if [ -e $LOGDIR/${_patch_name}-${_patch_ver}/post_patch.sh ]; then
       /bin/bash -x $LOGDIR/${_patch_name}-${_patch_ver}/post_patch.sh >> $LOGDIR/post_patch.log 2>&1
    fi
    $RM -f /nn/patches/blocking_flag
    if [ "$_umd_reboot" == "reboot" ]; then
       echo Apply_Reboot> $LOGDIR/active.status
       /sbin/shutdown -r now
    else
       echo "Restarting" > $LOGDIR/active.status
       if [ -e /nn/patches/strtree ]; then
          /nn/patches/strtree
       fi
       local _isleeps=0
       local _istarted=`processcontrol detaillist | grep Stopped | wc -l`
       /opt/sbin/monit monitor all
       while [ $_isleeps -lt 100 ] && [ $_istarted -gt $_istopped ]; do
          sleep 3
          let "_isleeps += 1"
          _istarted=`processcontrol detaillist | grep Stopped | wc -l`
       done
       echo Apply_Success > $LOGDIR/active.status
    fi
          
    return 0
}

#######################
remove_transaction () {
    local _patch_name=$1
    local _patch_ver=$2

    if [ ! "$_patch_name" ] || [ ! "$_patch_ver" ]; then
        return 2
    fi

    local _name
    local _ver
    local _str_tmn
    if [ ! -e $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.app ]; then
    #if ! cat $PATCH_CACHE | grep -i "${_patch_name}" | grep "${_patch_ver}" | grep -q -i Applied; then
        return 3
    fi
    if [ -e ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.obs ]; then
        return 4
    fi

    local _istopped=`processcontrol detaillist | grep Stopped | wc -l`
    local _tid=`$RPM -q --qf  "%{INSTALLTID}\n" ${_patch_name}-${_patch_ver}`  # check for exit code
    echo "INSTALL TID(${_patch_name}-${_patch_ver}): $_tid" >> /nn/patches/rback.log

    local _etid=""
    local _ltid=""
    # this will build an exclude list simply looking at all TIDs and ignoring those that less than
    # or equal to _tid, thus the resulting list will contain only thouse we want to exclude
    for _etid in `$RPM -qa --qf  "%{INSTALLTID}\n"`; do
        if [ $_etid -le $_tid ]; then
            continue
        fi
        if [ "$_ltid" ]; then
            _ltid="$_ltid $_etid"
        else
            _ltid=$_etid
        fi
    done
    local _rpm_desc
    local _rpm_rollback
    get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "DESCRIPTION" _rpm_desc
    #get_rpm_tag_value ${_patch_name}-${_patch_ver} "ALLOWROLLBACK" _rpm_rollback
    get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "ALLOWROLLBACK" _rpm_rollback    
    _rpm_rollback=`echo $_rpm_rollback | tr 'A-Z' 'a-z'`
    if [ ! $_rpm_rollback == "yes" ]; then
       return 5
    fi
    local _date_now=`date --date=now +%s`
    local _date_then=`expr $_date_now - $_tid + 10`
    echo "DATE NOW: $_date_now --- DATE THEN: $_date_then" >> /nn/patches/rback.log
    echo Removing > $LOGDIR/active.status
    if [ "$_ltid" ]; then
    	echo "$RPM_BIN -Uvh --rollback \"$_date_then seconds ago\" --rbexclude=\"$_ltid\"" >> /nn/patches/rback.log
    	echo "$RPM_BIN  --define '_rollback_transaction_on_failure 1' --define '_unsafe_rollbacks 1059710400' --define '_repackage_all_erasures 1'  -Uvvh --rollback \"$_date_then seconds ago\" --rbexclude=\"$_ltid\"" >> ${LOGDIR}/rpm.log
    	$($RPM_BIN  --define '_rollback_transaction_on_failure 1' --define '_unsafe_rollbacks 1059710400' --define '_repackage_all_erasures 1'  -Uvvh --rollback "$_date_then seconds ago" --rbexclude="$_ltid" >> ${LOGDIR}/rpm.log 2>&1); ret_code=$?

        #$($RPM_BIN -Uvh --rollback "`expr \`date --date=now +%s\` - $_tid` seconds ago" --rbexclude="$_ltid" >> ${LOGDIR}/rpm.log 2>&1)
    else
    	echo "$RPM_BIN -Uvh --rollback \"$_date_then seconds ago\""  >> /nn/patches/rback.log
    	echo "$RPM_BIN  --define '_rollback_transaction_on_failure 1' --define '_unsafe_rollbacks 1059710400' --define '_repackage_all_erasures 1'  -Uvvh --rollback \"$_date_then seconds ago\"" >> ${LOGDIR}/rpm.log 
    	$($RPM_BIN  --define '_rollback_transaction_on_failure 1' --define '_unsafe_rollbacks 1059710400' --define '_repackage_all_erasures 1'  -Uvvh --rollback "$_date_then seconds ago" >> ${LOGDIR}/rpm.log 2>&1); ret_code=$?

        #$($RPM_BIN -Uvh --rollback "`expr \`date --date=now +%s\` - $_tid` seconds ago" >> ${LOGDIR}/rpm.log 2>&1)
    fi

    if [ ! $ret_code -eq 0 ]; then
        error_alarm 2305 "Failed to remove software update. Ret=$ret_code"
        return 1
    else
        echo "SUCCESS: ($_patch_name -$ret_code- $_patch_ver)" >> /nn/patches/rback.log
    fi

    local _td=`date '+%a %b %d %H:%M:%S %Y'`

    ## History: Name, Version, ShortDescription, Category, AppliedDate, Removable
    printf "%s\t%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_rpm_desc" "Patch Removed" "$_td" "NotRemovable"  >> $PATCH_HISTORY

    while read line
    do
      `echo $line | grep -w "$_patch_name" | grep -w $_patch_ver | grep -w Removable >/dev/null 2>&1`
       ret_code=$?
       if [ $ret_code -eq 0 ]; then
          line=${line/	Removable/	NotRemovable}
          echo "$line" >> /nn/patches/info/history.tmp
       else
          echo "$line" >> /nn/patches/info/history.tmp
       fi
    done <$PATCH_HISTORY
    $RM -f $PATCH_HISTORY
    mv /nn/patches/info/history.tmp $PATCH_HISTORY

    $RM -f $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.app

    $RM -f ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.str
    $RM -f ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.trn
    $RM -f ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.end
    #$RM -f ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.log

    touch $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.ava
    echo "Restarting" > $LOGDIR/active.status
    if [ -e /nn/patches/strtree ]; then
       /nn/patches/strtree
    fi
    local _isleeps=0
    local _istarted=`processcontrol detaillist | grep Stopped | wc -l`
    /opt/sbin/monit monitor all
    while [ $_isleeps -lt 100 ] && [ $_istarted -gt $_istopped ]; do
       sleep 3
       let "_isleeps += 1"
       _istarted=`processcontrol detaillist | grep Stopped | wc -l`
    done

    echo Remove_Success > $LOGDIR/active.status
    info_alarm 2106 'Removed software update.'
    /opt/sbin/monit monitor all

    return 0
}

##############
get_times () {
    local _d=$1
    local _a=$2

    shift
    shift

    local _i=1
    local _arg=
    local _dw=
    local _ap=

    for _arg in $*; do
        if [ $_i -le 5 ]; then
            if [ "$_dw" ]; then
                _dw="$_dw $_arg"
            else
                _dw="$_arg"
            fi
        else
            if [ "$_ap" ]; then
                _ap="$_ap $_arg"
            else
                _ap="$_arg"
            fi
        fi
        let "_i=_i+1"
    done

    eval "${_d}=\"${_dw}\""
    eval "${_a}=\"${_ap}\""

    return 0
}

#########################
schedule_transaction () {
    local _patch_name=$1
    local _patch_ver=$2

    local _download
    local _apply
    local _umd_desc
    local _umd_rollback
    shift
    shift

    get_times _download _apply $*

    ### this is to handle scheduling done via EM method - folder on my computer, EM allows user to change and set apply time only,
    ### however softinv gets both download time and apply time anyway, where apply time is the one set/changed by the user via EM
    ### however download time stays same as at the time schedule was set, so in case of EM mode we simply need to download time same
    ### as apply time then transaction gets scheduled as single apply, note, anohter issue is simply when user does not increase
    ### apply time at all which by the time it arrives here is considered in past and the error is there
    if [ -e "${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.em" ]; then
        _download=$_apply
    fi
    
    if [ -n "$_download" ] && [ -n "$_apply" ]; then
        local _d_minute=$(date --date="${_download}" '+%M')
        local _d_hour=$(date --date="${_download}" '+%H')
        local _d_day=$(date --date="${_download}" '+%d')
        local _d_month=$(date --date="${_download}" '+%m')
        local _d_year=$(date --date="${_download}" '+%Y')

        local _a_minute=$(date --date="${_apply}" '+%M')
        local _a_hour=$(date --date="${_apply}" '+%H')
        local _a_day=$(date --date="${_apply}" '+%d')
        local _a_month=$(date --date="${_apply}" '+%m')
        local _a_year=$(date --date="${_apply}" '+%Y')

        local _d_sec=$(date --date="${_download}" '+%s')
        local _a_sec=$(date --date="${_apply}" '+%s')

        ### May not need to put given times through local time engine
        local _d_td=$(date --date="${_download}" '+%a %b %d %H:%M:%S %Y')
        local _a_td=$(date --date="${_apply}" '+%a %b %d %H:%M:%S %Y')

        ### checking if download time is at not greater then apply time, as mentioned somewhereelse, here we can check how different can download and apply
        ### time be, meaning, is there enough time for download to complete before apply kicks in, maybe apply can be postponed, but it should be handled  in apply or apply only
        if [ $_d_sec -gt $_a_sec ]; then
            return 1
        fi

        ### obviously, no need trying scheduling in past, check  only download time since apply should be later 
        local _sec_now=`date --date=now +%s`
        if [ $_sec_now -ge $_d_sec ]; then
            return 2
        fi

        local _umd_desc
        local _umd_reboot
        local _umd_size
        local _umd_rollback

        get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "DESCRIPTION" _umd_desc
        get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "REBOOT" _umd_reboot
        get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "SIZE" _umd_size
        get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "ALLOWROLLBACK" _umd_rollback
        
        _umd_reboot=`echo $_umd_reboot | tr 'A-Z' 'a-z'`
        _umd_rollback=`echo $_umd_rollback | tr 'A-Z' 'a-z'`

        local _removable
        if [ "$_umd_rollback" == "yes" ]; then
            _removable="Removable"
            else
            _removable="NotRemovable"
            fi

        if [ -e $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.ava ] && [ ! -e $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.scd ]; then    
            ### this item is available to be scheduled, if it has been already scheduled one have to first delete through modify option

            ### means the time you trying to schedule is less or equal to the time  of at least one item in your requires list
            check_requires $_patch_name $_patch_ver $_a_sec || return 3

            local _tmp_file_1=`mktemp -q /tmp/${PROGNAME}.XXXXXX` || exit 1

            local _display_path
            read _display_path < "$LOGDIR/location.log"

            printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_download" "$_apply" >$LOGDIR/$_patch_name-$_patch_ver.${ARCH}.umd.scd
            printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_umd_desc" "$_display_path" "$_download" "$_apply" "$_umd_reboot" "$_umd_size" "Scheduled" >>$LOGDIR/schedule.scd
        
            if [ $_d_sec -eq $_a_sec ]; then
                echo "${_d_minute} ${_d_hour} ${_d_day} ${_d_month} * /nn/bin/softinv --apply ${_patch_name} ${_patch_ver} > $LOGDIR/crontab.log 2>&1" > $_tmp_file_1
            else
                echo "${_d_minute} ${_d_hour} ${_d_day} ${_d_month} * /nn/bin/softinv --donly ${_patch_name} ${_patch_ver} > $LOGDIR/crontab.log 2>&1" > $_tmp_file_1
                echo "${_a_minute} ${_a_hour} ${_a_day} ${_a_month} * /nn/bin/softinv --aonly ${_patch_name} ${_patch_ver} > $LOGDIR/crontab.log 2>&1" >> $_tmp_file_1
        fi

            ### get current crontab spool into temporary file to add schedule this item, otherwise then entire crontab spool is overwritten, also double check if this item is already scheduled
            local _tmp_file_2=`mktemp -q /tmp/${PROGNAME}.XXXXXX` || exit 1
            /usr/bin/crontab -l 2>> /dev/null | /bin/egrep -v '^ *#|^ *$' > $_tmp_file_2 2>> /dev/null

            ### we also should check if there is any scheduling entry already about this item, although *.scd should have inidcated this already, let's assume the schedule simply was not cleared 
            ### upong completion, meaning, when scheduled item has completed it should cleared itself out of crontab spooling system

            cat $_tmp_file_1 >> $_tmp_file_2

            /usr/bin/crontab ${_tmp_file_2}

            $RM -f $_tmp_file_1
            $RM -f $_tmp_file_2

            local _td=`date '+%a %b %d %H:%M:%S %Y'`
        
            #History: Name, Version, ShortDescription, Category, AppliedDate, Removable
            printf "%s\t%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_umd_desc" "Scheduled" "$_td" "$_removable" >> $PATCH_HISTORY

        elif [ -e $LOGDIR/${_patch_name}-${_patch_ver}.${ARCH}.umd.scd ]; then
            ### this item has been already scheduled, modify or remove first, this also handled if the schedule is actually in crontab spooling system
            return 4
        else
            ### there is neither *.ava nor *.scd for this item
            ### this item can not be scheduled, it is not available, the logic should not actually get here unless used through CLI 
            return 5
        fi
    else
        # this is just to query for what has been schedule so far
        if `ls -1 ${LOGDIR}/*.scd >> /dev/null 2>&1`; then
            cat $LOGDIR/schedule.scd
        fi
    fi
    return 0
}

###################
check_requires () {
    local _patch_name=$1
    local _patch_ver=$2
    local _apply_time_sec=$3

    local _requires_list=
    local _requires=

    local _tmn=
    local _arg=
    local _name=
    local _ver=
    local _i=0
    local _dwn_tmn=
    local _app_tmn=
    local _sec_time_apply=

    ### we can not schedule an item that has an item in its requires list that has not been applied or scheduled to be applied prior to sched time of this item
    ### now, if the item is avalable it means the requires list has been satisfied, meaning every item is either already in rpm db or has been scheduled to get there
    ### we need to add one more rule here, this item's dwn/app times  must be greater than dwn/app times for every item in its requires scheduled list
    get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "REQUIRES" _requires_list

    ### so, here we really do not need to check whether requires list of this item has been satisfied, it is already known, otherewise the item would not be avalable
    for _requires in $_requires_list; do
        ### if at least one item in the list found to be scheduled then check whether the app time for this item is later, otherwise schedule can not go on
        ### we do not caser about download time, since it is guaranteed to be less then or equal to apply time, otherwise the item would not be scheduled
        if [ -e "${LOGDIR}/${_requires}.${ARCH}.umd.scd" ]; then

            read _name _ver _tmn < ${LOGDIR}/${_requires}.${ARCH}.umd.scd

            get_times _dwn_tmn _app_tmn $_tmn

            _sec_time_apply=$(date --date="${_app_tmn}" '+%s')
            if [ $_sec_time_apply -ge $_apply_time_sec ]; then
                ### only need to find one scheduled item that is scheduled later than this item inteded to be
                return 3
            fi
        fi
    done

    return 0
}

####################
modify_schedule () {
    local _patch_name=$1
    local _patch_ver=$2

    if [ ! "$_patch_name" ] || [ ! "$_patch_ver" ]; then
        return 5
    fi

    local _download=
    local _apply=
    shift
    shift

    get_times _download _apply $*

    ### in case of EM method, only apply is valid so just equate them
    if [ -e "${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.em" ]; then
        _download=$_apply
    fi

    if [ -e ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.scd ]; then

        ### indicates that this item was scheduled and still active

        local _tmn
        local _name
        local _ver

        ### _name and _ver should be same as _patch_name and _patch_ver respectively, do not really need it here ???
        read _patch_name _patch_ver _tmn < ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.scd
        local _dwn_tmn
        local _app_tmn
        
        get_times _dwn_tmn _app_tmn $_tmn

        local _minute_d=$(date --date="${_dwn_tmn}" '+%M')
        local _hour_d=$(date --date="${_dwn_tmn}" '+%H')
        local _day_d=$(date --date="${_dwn_tmn}" '+%d')
        local _month_d=$(date --date="${_dwn_tmn}" '+%m')
        local _year_d=$(date --date="${_dwn_tmn}" '+%Y')

        local _minute_a=$(date --date="${_app_tmn}" '+%M')
        local _hour_a=$(date --date="${_app_tmn}" '+%H')
        local _day_a=$(date --date="${_app_tmn}" '+%d')
        local _month_a=$(date --date="${_app_tmn}" '+%m')
        local _year_a=$(date --date="${_app_tmn}" '+%Y')

        local _sec_d=$(date --date="${_dwn_tmn}" '+%s')
        local _sec_a=$(date --date="${_app_tmn}" '+%s')

        local _d_minute=$(date --date="${_download}" '+%M')
        local _d_hour=$(date --date="${_download}" '+%H')
        local _d_day=$(date --date="${_download}" '+%d')
        local _d_month=$(date --date="${_download}" '+%m')
        local _d_year=$(date --date="${_download}" '+%Y')

        local _a_minute=$(date --date="${_apply}" '+%M')
        local _a_hour=$(date --date="${_apply}" '+%H')
        local _a_day=$(date --date="${_apply}" '+%d')
        local _a_month=$(date --date="${_apply}" '+%m')
        local _a_year=$(date --date="${_apply}" '+%Y')

        local _d_sec=$(date --date="${_download}" '+%s')
        local _a_sec=$(date --date="${_apply}" '+%s')
            
        ### this is going to hold current crontab system wide spooled items, we only edit patch revelvant items
        local _tmp_file_1=`mktemp -q /tmp/${PROGNAME}.XXXXXX` || exit 1
        local _tmp_file_2=`mktemp -q /tmp/${PROGNAME}.XXXXXX` || exit 1
        /usr/bin/crontab -l 2>> /dev/null | /bin/egrep -v '^ *#|^ *$' > $_tmp_file_1 2>> /dev/null

        if [ "$_download" ] && [ "$_apply" ]; then
            ### it is all or nothing situation, the scheduling can be change for both times only, not separately

        ### before doing anything else, let's check whether download time is less than or equal to apply time, only proceed if not
        ### can be enhanced to handle situation where delta between those two should take into account the time it takes for download
        ### however, apply may be allowd to schedule withing short period of time, however when during apply to wait untill download is done
        if [ "$_d_sec" -gt "$_a_sec" ]; then
            ### this is invalid schedule, return with error
            return 1;
                fi

        ### obviously, no need trying re-scheduling in past
        local _sec_now=`date --date=now +%s`
        if [ "$_download" ] && [ "$_apply" ] && [ $_sec_now -ge $_d_sec ]; then
                return 2
        fi

        ### check if there is any scheduled items in requires list and they've been scheduled before this scheduling time
        ### means the time you trying to schedule is less or equal to the time  of at least one item in your requires list
        check_requires $_patch_name $_patch_ver $_a_sec || return 3

            # if previously cheduled item was --apply only (means dwn and app time are same)
            if [ $_sec_d -eq $_sec_a ]; then

                # then if new dwn and app time are same then simply replace old --apply item with a new --apply item
            if [ $_d_sec -eq $_a_sec ]; then

                    ### here we need to look at system spool and delete previous entry, it should not be hard, we have all ingridients to describe previous scheduled same item

                    cat ${_tmp_file_1} | sed -e "s/^ *${_minute_d} ${_hour_d} ${_day_d} ${_month_d} \* \/nn\/bin\/softinv --apply ${_patch_name} ${_patch_ver} > \/nn\/patches\/info\/crontab.log 2>\&1 *$/${_d_minute} ${_d_hour} ${_d_day} ${_d_month} \* \/nn\/bin\/softinv --apply ${_patch_name} ${_patch_ver} > \/nn\/patches\/info\/crontab.log 2>\&1/" > ${_tmp_file_2}
            else
                    # else the old item was schedule as --apply and the new one should be split into dwn and app items, so, delete old -apply item and create a new (split into dwn and app) items
                    cat ${_tmp_file_1} | sed -e "s/^ *${_minute_d} ${_hour_d} ${_day_d} ${_month_d} \* \/nn\/bin\/softinv --apply ${_patch_name} ${_patch_ver} > \/nn\/patches\/info\/crontab.log 2>\&1 *$//" >> ${_tmp_file_2}
                    echo "${_d_minute} ${_d_hour} ${_d_day} ${_d_month} * /nn/bin/softinv --donly ${_patch_name} ${_patch_ver} > $LOGDIR/crontab.log 2>&1" >> ${_tmp_file_2}
                    echo "${_a_minute} ${_a_hour} ${_a_day} ${_a_month} * /nn/bin/softinv --aonly ${_patch_name} ${_patch_ver} > $LOGDIR/crontab.log 2>&1" >> ${_tmp_file_2}
                fi
            else
                # the previous schedule item was down separately per dwn and app times
                if [ $_d_sec -eq $_a_sec ]; then
                    # so new item should be schedule simply as --apply, thus delete dwn and app items and sched --apply

                    ### _tmp_file_1 holds system wide spooling information, first delete download scheduled entry and save it in _tmp_file_2 
                    cat ${_tmp_file_1} | sed -e "s/^ *${_minute_d} ${_hour_d} ${_day_d} ${_month_d} \* \/nn\/bin\/softinv --donly ${_patch_name} ${_patch_ver} > \/nn\/patches\/info\/crontab.log 2>\&1 *$//" > ${_tmp_file_2}

                    ### take _tmp_file_2 and delete apply scheduled entry from it, save in _tmp_file_1, overwrite it
                    cat ${_tmp_file_2} | sed -e "s/^ *${_minute_a} ${_hour_a} ${_day_a} ${_month_a} \* \/nn\/bin\/softinv --aonly ${_patch_name} ${_patch_ver} > \/nn\/patches\/info\/crontab.log 2>\&1 *$//" > ${_tmp_file_1}

                    ### now add single apply entry
                    echo "${_d_minute} ${_d_hour} ${_d_day} ${_d_month} * /nn/bin/softinv --apply ${_patch_name} ${_patch_ver} > $LOGDIR/crontab.log 2>&1" >> ${_tmp_file_1}

                    ### now move it all to _tmp_file_2, so that we eventually end up in a single file to feed to crontab 
                    cat ${_tmp_file_1} > ${_tmp_file_2}
                else
                    # old and new items were and will be done separately per dwn and app times

                    cat ${_tmp_file_1} | sed -e "s/^ *${_minute_d} ${_hour_d} ${_day_d} ${_month_d} \* \/nn\/bin\/softinv --donly ${_patch_name} ${_patch_ver} > \/nn\/patches\/info\/crontab.log 2>\&1 *$/${_d_minute} ${_d_hour} ${_d_day} ${_d_month} \* \/nn\/bin\/softinv --donly ${_patch_name} ${_patch_ver} > \/nn\/patches\/info\/crontab.log 2>\&1/" > ${_tmp_file_2}

                    cat ${_tmp_file_2} | sed -e "s/^ *${_minute_a} ${_hour_a} ${_day_a} ${_month_a} \* \/nn\/bin\/softinv --aonly ${_patch_name} ${_patch_ver} > \/nn\/patches\/info\/crontab.log 2>\&1 *$/${_a_minute} ${_a_hour} ${_a_day} ${_a_month} \* \/nn\/bin\/softinv --aonly ${_patch_name} ${_patch_ver} > \/nn\/patches\/info\/crontab.log 2>\&1/" > ${_tmp_file_1}

                    ### now move it all to _tmp_file_2, so that we eventually end up in a single file to feed to crontab
                    cat ${_tmp_file_1} > ${_tmp_file_2}

                fi
            fi
            local _d=$(date --date="${_download}"  '+%a %b %d %H:%M:%S %Y')
            local _a=$(date --date="${_apply}"  '+%a %b %d %H:%M:%S %Y')

            printf "%s\n" "${_patch_name} ${_patch_ver} $_d $_a" > ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.scd

            #### modify schedule cache
            while read line; do
                if ! echo $line | grep -w "$_patch_name" | grep -w "$_patch_ver" >/dev/null 2>&1; then
                    echo "$line" >> /nn/patches/info/schedule.tmp
                fi
            done < $LOGDIR/schedule.scd
            if [ ! -e /nn/patches/info/schedule.tmp ]; then
                /bin/touch /nn/patches/info/schedule.tmp
            fi
            mv -f /nn/patches/info/schedule.tmp /nn/patches/info/schedule.scd
            local _umd_desc
            get_package_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.uxd "DESCRIPTION" _umd_desc
            local _display_path
            read _display_path < "$LOGDIR/location.log"
            local _umd_reboot
            get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "REBOOT" _umd_reboot
            _umd_reboot=`echo $_umd_reboot | tr 'A-Z' 'a-z'`
            local _umd_size
            get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "SIZE" _umd_size

            printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_umd_desc" "$_display_path" "$_download" "$_apply" "$_umd_reboot" "$_umd_size" "Scheduled" >>$LOGDIR/schedule.scd

        else
            # this is a simple remove item from the schedule, so just remove it
            if [ "$_sec_d" = "$_sec_a" ]; then
                cat ${_tmp_file_1} | sed -e "s/^ *${_minute_d} ${_hour_d} ${_day_d} ${_month_d} \* \/nn\/bin\/softinv --apply ${_patch_name} ${_patch_ver} > \/nn\/patches\/info\/crontab.log 2>\&1 *$//" > ${_tmp_file_2}
            else
                cat ${_tmp_file_1} | sed -e "s/^ *${_minute_d} ${_hour_d} ${_day_d} ${_month_d} \* \/nn\/bin\/softinv --donly ${_patch_name} ${_patch_ver} > \/nn\/patches\/info\/crontab.log 2>\&1 *$//" > ${_tmp_file_2}

                cat ${_tmp_file_2} | sed -e "s/^ *${_minute_a} ${_hour_a} ${_day_a} ${_month_a} \* \/nn\/bin\/softinv --aonly ${_patch_name} ${_patch_ver} > \/nn\/patches\/info\/crontab.log 2>\&1 *$//" > ${_tmp_file_1}

                ### now move it all to _tmp_file_2, so that we eventually end up in a single file to feed to crontab
                cat ${_tmp_file_1} > ${_tmp_file_2}
            fi


            $RM -f ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.scd
            while read line; do
                if ! echo $line | grep -w "$_patch_name" | grep -w "$_patch_ver" >/dev/null 2>&1; then
                    echo "$line" >> /nn/patches/info/schedule.tmp
                fi
            done <$LOGDIR/schedule.scd
            if [ ! -e /nn/patches/info/schedule.tmp ]; then
                /bin/touch /nn/patches/info/schedule.tmp
            fi
            mv -f /nn/patches/info/schedule.tmp /nn/patches/info/schedule.scd
        fi

        /usr/bin/crontab ${_tmp_file_2}
        $RM -f $_tmp_file_1
        $RM -f $_tmp_file_2

        ### FROMAPPLY global indicates that scheduled item was applied, so, just want to remove scheduling info, 
        ### no need to reflect it history, since applie history takes care of it
        if [ "X$FROM_APPLY" != "XTRUE" ]; then
            local _td=`date '+%a %b %d %H:%M:%S %Y'`
            local _act
            if [ "$_download" ] && [ "$_apply" ]; then
                _act="Patch Schedule Modified"
            else
                _act="Patch Schedule Removed"
            fi
                
            local _umd_desc
            local _umd_rollback
            get_package_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.uxd "DESCRIPTION" _umd_desc
            get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "ALLOWROLLBACK" _umd_rollback
            _umd_rollback=`echo $_umd_rollback | tr 'A-Z' 'a-z'`
        
            #History: Name, Version, ShortDescription, Category, AppliedDate, Removable
            if [ $_umd_rollback == "no" ] || [ -e ${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.obs ]; then
                printf "%s\t%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_umd_desc" "$_act" "$_td" "NotRemovable" >> $PATCH_HISTORY
            else
                printf "%s\t%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_umd_desc" "$_act" "$_td" "Removable" >> $PATCH_HISTORY
            fi
        fi

    else
        ### this item was not scheduled, schedule first to modify, should not get here unless via CLI
        return 5
    fi

    return 0
}

#####################
remove_schedule () {

    local _scd_file
    local _patch_name
    local _patch_ver
    local _the_rest

    ### we are going to utilize modify_schedule here since if get only name and version of patch it deletes it
    for _scd_file in `ls -1 ${LOGDIR}/*.scd`; do
        if [ "$_scd_file" == "${LOGDIR}/schedule.scd" ]; then
            continue
        fi
        read _patch_name _patch_ver _the_rest < $_scd_file
        modify_schedule $_patch_name $_patch_ver
    done
    return 0
}

################
query_apply () {
        # this is just to query for what has been schedule so far
        if `ls -1 ${LOGDIR}/*.str >> /dev/null 2>&1`; then
            local _str_tmn
            local _str_file
            local _patch_name
            local _patch_ver
            local _umd_desc
            local _umd_reboot
            local _patch_proto
            local _patch_size
            local _location
            
            for _str_file in `ls -1 ${LOGDIR}/*.str`; do
                read _patch_name _patch_ver _str_tmn < ${_str_file}
                if [ -e "${LOGDIR}/${_patch_name}-${_patch_ver}.${ARCH}.umd.end" ]; then
                    continue
                fi
                read _location < $LOGDIR/location.log
                validate_path "$_location"
                get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "DESCRIPTION" _umd_desc
                get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "REBOOT" _umd_reboot
                get_umd_tag_value $LOGDIR ${_patch_name}-${_patch_ver}.${ARCH}.umd "SIZE" _umd_size
                _umd_reboot=`echo $_umd_reboot | tr 'A-Z' 'a-z'`
                printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" "$_patch_name" "$_patch_ver" "$_umd_desc" "$_remote_path" "$_str_tmn" "$_umd_size" "Active" "$_umd_reboot"
            done
        fi

    return 0
}

########################
optional_selections () {
    local _patch=$1-$2

    shift;shift

	local _optional_select="$*"
	
	### if not optional selection made, no need to do anything
    if [ "X$_optional_select" == "X" ]; then
		return 1
	fi

	local _optional_select=" $_optional_select "


   local _rpm=
   $RM -f $LOGDIR/${_patch}.${ARCH}.umd.opts.tmp > /dev/null 2>&1 
   $TOUCH $LOGDIR/${_patch}.${ARCH}.umd.opts.tmp > /dev/null 2>&1
   for _rpm in $_optional_select; do
	   $ECHO "$_rpm" >> $LOGDIR/${_patch}.${ARCH}.umd.opts.tmp
   done

    $RM -f $LOGDIR/${_patch}.${ARCH}.umd.opts.tmp.tmp
    $TOUCH $LOGDIR/${_patch}.${ARCH}.umd.opts.tmp.tmp

    local _savIFS=$IFS
    IFS=$'\n'
    for _rpm in `cat $LOGDIR/${_patch}.${ARCH}.umd.opts`; do
        if ! $GREP -q "$_rpm" $LOGDIR/${_patch}.${ARCH}.umd.opts.tmp; then
            echo "$_rpm" >> $LOGDIR/${_patch}.${ARCH}.umd.opts.tmp.tmp
        fi
    done
   IFS="$_savIFS"
   $CP -f $LOGDIR/${_patch}.${ARCH}.umd.opts.tmp.tmp $LOGDIR/${_patch}.${ARCH}.umd.opts > /dev/null 2>&1
   $RM -f $LOGDIR/*.tmp > /dev/null 2>&1

    $RM -f $LOGDIR/${_patch}.${ARCH}.umd.rpms.tmp > /dev/null 2>&1
    $TOUCH $LOGDIR/${_patch}.${ARCH}.umd.rpms.tmp > /dev/null 2>&1
    local _savIFS=$IFS
    IFS=$'\n'
    for _rpm in `cat $LOGDIR/${_patch}.${ARCH}.umd.rpms`; do
        _rpm=`$ECHO "$_rpm" | $SED -e "s/\.${ARCH}\.rpm$//"`
        if ! $GREP -q "$_rpm" $LOGDIR/${_patch}.${ARCH}.umd.opts; then
            echo "$_rpm.${ARCH}.rpm" >> $LOGDIR/${_patch}.${ARCH}.umd.rpms.tmp
        fi
    done
   IFS="$_savIFS"
   cp -f $LOGDIR/${_patch}.${ARCH}.umd.rpms.tmp $LOGDIR/${_patch}.${ARCH}.umd.rpms > /dev/null 2>&1
    return 0

}

#################
write_status () {
    local _file=$1
    local _status_msg=$2

    ### maybe need to note a change of status in log file
    echo "${_status_msg}" > ${_file}
    return 0
}

################
read_status () {
    local _file=$1

    local _msg=
    local _current_status=
    local _current_msg=
    local _patch_name=
    local _package=

    if [ -e "${_file}" ] && [ -s "${_file}" ]; then
        _msg=`cat $_file`
        _current_status=`echo $_msg | sed -e 's/^ *\([^ ][^ ]*\)  *.*$/\1/'`
        _current_msg=`echo $_msg | sed -e 's/^ *[^ ][^ ]*  *//'`
    else
        _current_status="Failed"
        _current_msg="Unknown Failure"
    fi

    if [ "X$_current_msg" == "X" ]; then
        _current_msg="Unknown Failure"
    fi
    if [ -e "/nn/patches/info/running_package" ]; then
       _package=`cat /nn/patches/info/running_package`
    else
       _package= 
    fi
    case $_current_status in 
### ++++++++++++++++++++++++
        "Connection_Failed")
            echo -e "-1\t$_current_msg"
            ;;
        "File_Not_Found")
            echo -e "-1\t$_current_msg"
            ;;
        "Directory_Not_Found")
            echo -e "-1\t$_current_msg"
            ;;
        "Connection_Refused")
            echo -e "-1\t$_current_msg"
            ;;
        "Authorization_Failed")
            echo -e "-1\t$_current_msg"
            ;;
        "Login_Incorrect")
            echo -e "-1\t$_current_msg"
            ;;
        "Host_Not_Found")
            echo -e "-1\tCannot contact remote host. Please verify address."
            ;;
        "Host_Unreachable")
            echo -e "-1\t$_current_msg"
            ;;
        "System_Error")
            echo -e "-1\t$_current_msg"
            ;;
        "No_Files")
            echo -e "-1\t$_current_msg"
            ;;
        "Scanning_Start")
            echo -e "0\tStarting Updates Search $_current_msg"
            ;;
        "Scanning")
            echo -e "0\tSearching Updates ... $_current_msg"
            ;;
        "Downloading_Patches")
            echo -e "0\tDownloading ... $_current_msg"
            ;;
        "Scanning_Done")
            echo -e "0\tDone Searching for Updates $_current_msg"
            ;;
        "Building_Start")
            echo -e "0\tComparing Updates to system $_current_msg"
            ;;
        "Building_End")
            echo -e "1\tDone Comparing$_current_msg"
            ;;
        "DB_Error")
            echo -e "-1\t$_current_msg"
            ;;
        "Build_Error")
            echo -e "-1\t$_current_msg"
            ;;
        "Download_Start")
            echo -e "0\tDownloading update content"
            ;;
        "Download_End")
            echo -e "0\tFinished downloading"
            ;;
        "Apply_Start")
            #echo -e "0\tStart Applying Updates"
            echo -e "0\tPreparing to update"
            ;;
        "Apply_End")
            echo -e "0\tApplying Updates Done"
            ;;
        "Verifying_Signatures")
            echo -e "0\tDoing Checksums on updates content"
            ;;
        "Failed_Key")
            echo -e "-1\t$_current_msg"
            ;;
        "Failed_Decrypt")
            echo -e "-1\tDecryption Mechanism Failure"
            ;;
### ------------------------
       "Working")
             echo -e "0\tWorking"
             ;;
       "Building")
             echo -e "0\tValidating Updates"
             ;;
       "Built")
             echo -e "1\tDone"
             ;;
       "Scanning")
             echo -e "0\tSearching..."
             ;;
       "Starting")
             echo -e "0\tStarting"
             ;;
       "Restarting")
             echo -e "0\tInitializing"
             ;;
       "Apply_Reboot")
             echo -e "2\tSuccess...Rebooting"
             $RM -f /nn/patches/info/active
             $RM -f /nn/patches/info/running_package
             $RM -f /nn/patches/info/*.status
             ;;
       "Apply Success")
             echo -e "1\tApplied"
             $RM -f /nn/patches/info/active
             $RM -f /nn/patches/info/running_package
             $RM -f /nn/patches/info/*.status
             ;;       
       "Apply_Success")
             echo -e "1\tApplied"
             $RM -f /nn/patches/info/active
             $RM -f /nn/patches/info/running_package
             $RM -f /nn/patches/info/*.status
             ;;
       "Downloading")
              _percent_complete=
             if [ -e $LOGDIR/startsize ] && [ -e $LOGDIR/totalsize ]; then
               read _start_size <$LOGDIR/startsize
               read _total_size <$LOGDIR/totalsize
               _curr_size=`du -mSs $LOGDIR`
               for _info_size in $_curr_size; do
                 break
               done
               echo `date` "$_info_size-$_start_size)*100/$_total_size" >$LOGDIR/downloading.log
               let _percent_complete=($_info_size-$_start_size)*100/$_total_size
               _percent_complete=$_percent_complete'%'
             fi
             echo "0    Downloading...$_percent_complete" >$LOGDIR/downloading.log
             echo "0	Downloading...$_percent_complete"
             ;;
       "Downloaded")
             echo -e "0\tDownloaded"
             ;;
       "Download_Failed")
             echo -e "-1\tDownload failed"
             $RM -f /nn/patches/info/active
             $RM -f /nn/patches/info/running_package
             $RM -f /nn/patches/info/*.status
             ;;
       "Connect_Failed")
            echo -e "-1\tConnection Failure"
            $RM -f /nn/patches/info/active
            $RM -f /nn/patches/info/running_package
            $RM -f /nn/patches/info/*.status
           ;;
        "Login_Failed")
             echo -e "-1\tCredentials/URL Failure"
             $RM -f /nn/patches/info/active
             $RM -f /nn/patches/info/running_package
             $RM -f /nn/patches/info/*.status
            ;;
       "Apply_Failed")
             echo -e "-1\tApply failed"
             $RM -f /nn/patches/info/active
             $RM -f /nn/patches/info/running_package
             $RM -f /nn/patches/info/*.status
             ;;
       "Applying")
             if [ -n $_package ] && [ -e $LOGDIR/$_package.log ]; then
                cat $LOGDIR/$_package.log
             fi
             read _active_patch <$LOGDIR/active
             local _progress=
             _upgrade_log=$LOGDIR/$_active_patch.log
             if [ -e $LOGDIR/upgrading ] && [ -e $_upgrade_log ]; then
                 _num_complete=0
                 _num_complete=`cat $_upgrade_log | grep adding | grep Name | wc -l`
                 if [ $_num_complete == 0 ]; then
                    echo "0    Preparing..."
                    exit 0
                 fi
                 _num_total=0
                 _num_extra=0
                 _num_total=`cat $LOGDIR/$_active_patch.${ARCH}.umd.rpms | wc -l`
                 (( _num_total = _num_total + 1 ))
                 if [ -e $LOGDIR/$_active_patch.${ARCH}.umd.rpms1 ]; then
                    _num_extra=`cat $LOGDIR/$_active_patch.${ARCH}.umd.rpms1 | wc -l`
                    (( _num_total = _num_total + _num_extra ))
                 fi                 
                 _progress="$_num_complete\\$_num_total"
             fi
             echo "0	Applying...$_progress"
             ;;
       "Failed")
             echo -e "-1\tFailed activity"
             $RM -f /nn/patches/info/active
             $RM -f /nn/patches/info/running_package
             $RM -f /nn/patches/info/*.status
             ;;
       "Failed_TZ")
             echo -e "-1\t${_current_msg}"
             #$RM -f /nn/patches/info/active
             #$RM -f /nn/patches/info/running_package
             #$RM -f /nn/patches/info/*.status
             ;;
       "Failed_Sigs")
             echo -e "-1\tInvalid or corrupt patch. Please try retrieving the patch again."
             $RM -f /nn/patches/info/active
             $RM -f /nn/patches/info/running_package
             $RM -f /nn/patches/info/*.status
             ;;
       "Verifying")
             echo -e "0\tVerifying files"
             ;;
       "*")
             echo -e '-1\tFailed activity'
             $RM -f /nn/patches/info/active
             $RM -f /nn/patches/info/running_package
             $RM -f /nn/patches/info/*.status
             ;;
     esac

     return 0
}

##########
usage () {
    echo >&2 "${PROGNAME}:" "$@"
    echo >&2 "Usage: $PROGNAME [options]"
    echo >&2 "--ftp <ftp ip address> <user name> <user password> <remote path (relative)>"
    echo >&2 "--http <http address> <user name> <user password> <remote path (relative)>"
    echo >&2 "--https <https address> <user name> <user password> <remote path (relative)>"
    echo >&2 "--samba <address> <user name> <user password> <remote path (relative)> <domain>"
    echo >&2 "--usb <path>"
    echo >&2 "--em"
    echo >&2 "--cache"
    echo >&2 "--apply <patch name> <patch version>"
    echo >&2 "--apply"
    echo >&2 "--rback <patch name> <patch version>"
    echo >&2 "--sched <patch name> <patch version> <download time> <apply time>"
    echo >&2 "--sched"
    echo >&2 "--msched <patch name> <patch version> <download time> <apply time>"
    echo >&2 "--msched <patch name> <patch version>"
    echo >&2 "--hist"
    echo >&2 "--files"
    echo >&2 "--hascomponents <patch name> <patch version>"
    echo >&2 "--components <patch name> <patch version>"
    echo >&2 "--help"
    echo >&2 "--errors"
    exit 10
}

###########
errors () {
    local _err_num=$1
    case $_err_num in
        11)
            echo "${_err_num}: Failed to connect to ftp server." 
            ;;
        12)
            echo "${_err_num}: Failed to apply software update." 
            ;;
        13)
            echo "${_err_num}: Failed to apply transaction"
            ;;
        131)
            echo "${_err_num}: Internal apply error"
            ;;
        132)
            echo "${_err_num}: Attempt to apply transaction that avalable for scheduling only"
            ;;
        133)
            echo "${_err_num}: Attempt to apply patch during active patch/upgrade process"
            ;;
        134)
            echo "${_err_num}: Failed to install RPM(s) - check your patch"
            ;;
        14)
            echo "${_err_num}: Failed to download patch"
            ;;
        15)
            echo "${_err_num}: Failed to apply patch"
            ;;
        16)
            echo "${_err_num}: Failed to remove patch"
            ;;
        17)
            echo "${_err_num}: Faild to schedule patch"
            ;;
        171)
            echo "${_err_num}: Download time is later then apply - correct this"
            ;;
        172)
            echo "${_err_num}: Attempt to schedule in past, why? - correct this"
            ;;
        173)
            echo "${_err_num}: Increase tranasaction apply time to satisfy requires"
            ;;
        174)
            echo "${_err_num}: Attempt to schedule already scheduled item"
            ;;
        175) 
             echo "${_err_num}: Internal scheduler error - report to support"
            ;;
        18)
            echo "${_err_num}: Failed to modify scheduled patch"
            ;;
        19)
            echo "${_err_num}: Failed to connect to http server or incorrect credentials." 
            ;;
        20)
            echo "${_err_num}: Failed to connect to https server or incorrect credentials." 
            ;;
        21)
            echo "${_err_num}: Failed to connect to samba server or incorrect credentials."
            ;;
        22)
            echo "${_err_num}: Failed to connect to usb device or incorrect path." 
            ;;
        23)
            echo "${_err_num}: No patches found." 
            ;;
        24)
            echo "${_err_num}: No patches found in local directory."
            ;;
        26)
            echo "${_err_num}: URL/PATH not found"
            ;;
        27)
            echo "${err_num}: HOST not found"
            ;;
        28)
            echo "${_err_num}: LOGIN incorrect"
            ;;
        29)
            echo "${_err_num}: WGET error"
            ;;
        33)
            echo "${_err_num}: No patches found in local directory.."
            ;;
        34)
            echo "${_err_num}: Time zone on system must be set before performing software maintenance."
            ;;
        35)
            echo "${_err_num}: Error removing all scheduled items."
            ;;


        *)
            echo "Supported Errors"
            echo "ftp_ERROR=11"
            echo "APPLY_ERROR1=12"

            echo "APPLY_ERROR=13"
            echo "APPLY_ERROR_1=131"
            echo "APPLY_ERROR_2=132"
            echo "APPLY_ERROR_3=133"
            echo "APPLY_ERROR_4=134"

            echo "DONLY_ERROR=14"
            echo "AONLY_ERROR=15"
            echo "RBACK_ERROR=16"

            ### scheduling somethign errors
            echo "SCHED_ERROR=17"
            echo "SCHED_ERROR_1=171"
            echo "SCHED_ERROR_2=172"
            echo "SCHED_ERROR_3=173"
            echo "SCHED_ERROR_4=174"
            echo "SCHED_ERROR_5=175"

            echo "MSCHED_ERROR=18"
            echo "http_ERROR=19"
            echo "httpS_ERROR=20"
            echo "samba_ERROR=21"
            echo "usb_ERROR=22"
            echo "BUILD_LIST_ERROR=23"
            echo "ERROR_WGET_PATH=26"
            echo "ERROR_WGET_HOST=27"
            echo "ERROR_WGET_LOGIN=28"
            echo "ERROR_WGET_GEN=29"

            echo "em_ERROR=33"
            echo "ERROR_DATE_TZ=34"
            echo "RSCHED_ERROR=35"
            ;;
    esac
    return 0
}

#################
list_warnings() {
    if [ ! $# == 2 ]; then
       return 1
    fi
    local _patch_id=$1-$2
    warnings_list=
    if [ ! -e $LOGDIR/$_patch_id.warning ]; then
       echo "Minimal impact to system performance for the duration of the software update." >>$LOGDIR/warnings.list
    fi
    if `cat $LOGDIR/$_patch_id.warning | grep 1 >/dev/null 2>&1`; then
       #warnings_list="Automatic reboot upon completion of the update."
       echo "Automatic reboot upon completion of the update." >$LOGDIR/warnings.list
    fi
    if `cat $LOGDIR/$_patch_id.warning | grep 2 >/dev/null 2>&1`; then
       #warnings_list="$warnings_list Temporary loss of system functionality for the duration of the update."
       echo "Service interruption for the duration of the update." >>$LOGDIR/warnings.list
    fi
    if `cat $LOGDIR/$_patch_id.warning | grep 3 >/dev/null 2>&1`; then
       #warnings_list="$warnings_list Loss of network connectivity for the duration of the update."
       echo "Loss of network connectivity for the duration of the update." >>$LOGDIR/warnings.list
    fi
    if `cat $LOGDIR/$_patch_id.warning | grep 4 >/dev/null 2>&1`; then
       #warnings_list="$warnings_list Loss of modem connectivity for the duration of the update."
       echo "Loss of modem connectivity for the duration of the update." >>$LOGDIR/warnings.list
    fi
}
    

###############
valid_date () {

    ### the following needs to be moved somewhere into init section
    chmod 0755 /nn
    chmod 0755 /nn/patches
    chmod 0755 /nn/patches/info
    chmod 0755 /nn/patches/tmp
    chown www:www /nn/patches/tmp
    ###############################################################
    
    if date | grep -i 'Local time zone must be set'; then
        DATE_ERR_MSG="${DATE}: Local time zone must be set prior to applying software updates. Please set the time zone and try again."
        return 1
    fi
    return 0
}

#################
##### MAIN ######
#################

### GLOBALS #####
PROGNAME=`basename $0`

### progrname and tempfiles should be done this way
progname=${0##*/}
# tempfile=$(mktemp $progname.XXXXXX) || exit 5

LOGDIR=/nn/patches/info
if [ ! -d "$LOGDIR" ]; then
   mkdir $LOGDIR
fi
INVENTORY_LOG="$LOGDIR/softwareinventory.log"
RPM_BIN="/usr/local/bin/rpm"
CRON_BIN="/usr/bin/crontab"
PATCH_HISTORY_LOG="$LOGDIR/patch_history.log"
RELEASE_HISTORY_LOG="/var/nn/release_history.info"
PATCH_CACHE="$LOGDIR/cache.log"
PATCH_LOG="/var/log/softwareupdates.log"
LOG_FILE=`basename /var/log/softwareupdates.log`
PATCH_HISTORY="$LOGDIR/history.log"

replace_rpm_if_necessary;

### initialization section
if [ ! -e "$LOGDIR/readme" ]; then
    mkdir -p $LOGDIR/readme
fi

### if can not decude ARCH, set status and exit
if ! get_arch ARCH; then
    #echo -e "-1\tSystem Failure: Unknown Platform" > $LOGDIR/active.status
    exit 0
fi

### suffies for now but this should somewhere in the initialization section
if [ "X$ARCH" == "Xppc" ]; then
    USBDEV="sdb1"
else
    USBDEV="sda1"
fi

METHOD=
##########################

case "$1" in
    "") 
        $RPM_BIN -qa --queryformat \
            '%{NAME}\t%{VERSION}-%{RELEASE}\tOperating System\t%{INSTALLTIME:date}\n' > $INVENTORY_LOG;
        cat $INVENTORY_LOG
        exit 0;
        ;;
    "--ftp" | "--http" | "--https" | "--samba" | "--usb" | "--em")
        METHOD=`echo $1 | sed -e 's/^--//'`
        shift
        if [ -e $LOGDIR/cache.log ]; then
           rm -f $LOGDIR/cache.log
        fi

        #write_status "$LOGDIR/active.status" "Scanning_Start"
        info_log "Start Scanning $METHOD "

        if ! valid_date; then
            write_status "$LOGDIR/active.status" "Failed_TZ ${DATE_ERR_MSG}"
            error_log "${DATE_ERR_MSG} "
            exit 0
        fi

        if [ "X$METHOD" == "Xftp" ]; then
            if ! scan_ftp_location $*; then
                write_status "$LOGDIR/active.status" "$SCAN_ERR_MSG"
                error_log "$SCAN_ERR_MSG"
                exit 0
            fi
        elif [ "X$METHOD" == "Xhttp" ] || [ "X$METHOD" == "Xhttps" ]; then
            ### note: EM never does --https call, it is always -http with either false or true=ssl laster argument
            ###       running via cli, one needs to supplie true/false as the alst argument to idicate whether secure or not
            ###       --https here is just for completeness, actually just say true when ssl otherwise nothing needs to be done
            if ! scan_http_location $*; then
                write_status "$LOGDIR/active.status" "$SCAN_ERR_MSG"
                error_log "$SCAN_ERR_MSG"
                exit 0
            fi
        elif [ "X$METHOD" == "Xsamba" ]; then
            if ! scan_samba_location $*; then
                write_status "$LOGDIR/active.status" "$SCAN_ERR_MSG"
                error_log "$SCAN_ERR_MSG"
                exit 0
            fi
        elif [ "X$METHOD" == "Xusb" ]; then
            if ! scan_usb_location $*; then
                write_status "$LOGDIR/active.status" "$SCAN_ERR_MSG"
                error_log "$SCAN_ERR_MSG"
                exit 0
            fi
        elif [ "X$METHOD" == "Xem" ]; then
            if [ ! -d /nn/patches/tmp ]; then
                mkdir -p > /dev/null 2>&1 
            fi
            if ! scan_EM_location $*; then
                write_status "$LOGDIR/active.status" "$SCAN_ERR_MSG"
                error_log "$SCAN_ERR_MSG"
                exit 0
            fi
        fi
        write_status "$LOGDIR/active.status" "Scanning_Done"
        info_log "Done Scanning $METHOD "

        #write_status "$LOGDIR/active.status" "Building_Start"
        info_log "Start Building from $METHOD <- $LINENO of $PROGNAME"

        if ! build_list; then
            write_status "$LOGDIR/active.status" "$BUILD_ERR_MSG"
            info_log "$BUILD_ERR_MSG <- $LINENO of $PROGNAME"
            exit 0
        fi
        write_status "$LOGDIR/active.status" "Building_End"
        info_log "Done Building from $METHOD <- $LINENO of $PROGNAME"

        $RM -f /nn/patches/tmp/*
        $RM -rf $_TMP_DIR
        ;;
    "--cache")
        shift
        if [ -e $PATCH_CACHE ]; then
            cat $PATCH_CACHE
        fi
        ;;
    "--apply")
        shift
        _args=$*
        if [ -n "$_args" ]; then
            if ! valid_date; then
                write_status $LOGDIR/active.status "Failed_TZ ${DATE_ERR_MSG}"
                error_log "Failed_TZ ${DATE_ERR_MSG} <- $LINENO of $PROGNAME"
                exit 0
            fi
            write_status "$LOGDIR/active.status" "Download_Start"
            info_log "Download_Start <- $LINENO of $PROGNAME"
            
            echo $1 > /nn/patches/info/active

			if ! optional_selections $*; then
				info_log "Apperently nothing selected optionally"
			fi

            if ! download_patch $*; then
                if [ "X$DWNLD_ERR_MSG" == "X" ]; then
                    DWNLD_ERR_MSG="Download_Failed "
                fi
                write_status "$LOGDIR/active.status" "$DWNLD_ERR_MSG"
                error_log "$DWNLD_ERR_MSG <- $LINENO of $PROGNAME"
                exit 0
            fi

            write_status "$LOGDIR/active.status" "Download_End"
            info_log "Download_End <- $LINENO of $PROGNAME"

            write_status "$LOGDIR/active.status" "Apply_Start"
            info_log "Apply_Start <- $LINENO of $PROGNAME"

            if ! apply_patch $*; then
                write_status "$LOGDIR/active.status" "Apply_Failed"
                info_log "Apply_Failed <- $LINENO of $PROGNAME"
                 exit  0 ### $APPLY_ERROR
            fi
            write_status "$LOGDIR/active.status" "Apply_Success"
            info_log "Apply_Success <- $LINENO of $PROGNAME"
        else
            ### just query updates currently being applied
            query_apply
        fi
        ;;
    "--donly")
        shift
        if ! valid_date; then
            write_status $LOGDIR/active.status "Failed_TZ ${DATE_ERR_MSG}"
            error_log "Failed_TZ ${DATE_ERR_MSG} <- $LINENO of $PROGNAME"
            exit 0
        fi

        write_status "$LOGDIR/active.status" "Download_Start"
        info_log "Download_Start <- $LINENO of $PROGNAME"
        if ! download_patch $*; then
            if [ "X$DWNLD_ERR_MSG" == "X" ]; then
                DWNLD_ERR_MSG="Download_Failed <- $LINENO of $PROGNAME"
            fi
            write_status "$LOGDIR/active.status" "$DWNLD_ERR_MSG"
            error_log "$DWNLD_ERR_MSG <- $LINENO of $PROGNAME"
            exit 0
        fi
        write_status "$LOGDIR/active.status" "Download_End"
        info_log "Download_End <- $LINENO of $PROGNAME"
        ;;            
    "--aonly")
        shift
        if ! valid_date; then
            write_status $LOGDIR/active.status "Failed_TZ ${DATE_ERR_MSG}"
            error_log "Failed_TZ ${DATE_ERR_MSG} <- $LINENO of $PROGNAME"
            exit 0
        fi
        if ! apply_patch $*; then
            exit 0 ### $AONLY_ERROR
        fi
        ;;            
    "--rback")
        shift
        if ! valid_date; then
            write_status $LOGDIR/active.status "Failed_TZ ${DATE_ERR_MSG}"
            error_log "Failed_TZ ${DATE_ERR_MSG} <- $LINENO of $PROGNAME"
            exit 0
        fi
        echo $* >> /nn/patches/rback.log
        if ! remove_transaction $*; then
            ### need to update active status
            exit 0 ### $RBACK_ERROR
        fi
        ;;
    "--sched")
        shift
        _args=$*
        if [ -n "$_args" ]; then
            if ! valid_date; then
                write_status $LOGDIR/active.status "Failed_TZ ${DATE_ERR_MSG}"
                error_log "Failed_TZ ${DATE_ERR_MSG} <- $LINENO of $PROGNAME"
                exit 0
            fi
        fi
        schedule_transaction $*
        ret_code=$?
        case $ret_code in
            0)
                ### scheduled OK
                ;;
            1)
                ### download time is later than apply time
                exit 0 ### $SCHED_ERROR_1
                ;;
            2) 
                ### attem to schedule in past, why ???
                exit 0
                ;;
            3)
                ### must increase transaction apply time to satisfy requires
                exit 0 ### $SCHED_ERROR_3
                ;;
            4)
                ### attempt to schedule already scheduled transaction, delete first
                exit 0 ### $SCHED_ERROR_4
                ;;
            5)
                ### internal error to scheduler, should really be reported to support
                exit 0 ### $SCHED_ERROR_5
                ;;
            *)
                ### general sched error, just to catch new error conditions, othewise success maybe reportedo  
                exit 0 ### $SCHED_ERROR
                ;;
        esac
        ;;        
    "--msched")
        shift
        if ! valid_date; then
            write_status $LOGDIR/active.status "Failed_TZ ${DATE_ERR_MSG}"
            error_log "Failed_TZ ${DATE_ERR_MSG} <- $LINENO of $PROGNAME"
            exit 0
        fi
        modify_schedule $*
        ret_code=$?
        case $ret_code in
            0)
                ### scheduled OK
                ;;
            1)
                ### download time is later than apply time
                exit 0 ### $SCHED_ERROR_1
                ;;
            2)
                ### attem to schedule in past, why ???
                exit 0 ### $SCHED_ERROR_2
                ;;
            3)
                ### must increase transaction apply time to satisfy requires
                exit 0 ### $SCHED_ERROR_3
                ;;
            # 4) ### no such a case for now
            5)
                ### internal error to scheduler, should really be reported to support
                exit 0 ###  $SCHED_ERROR_5
                ;;
            *)
                ### general sched error, just to catch new error conditions, othewise success maybe reportedo
                exit 0 ### $SCHED_ERROR
                ;;
        esac
        ;;        
    "--rsched")
        shift
        if ! valid_date; then
            write_status $LOGDIR/active.status "Failed_TZ ${DATE_ERR_MSG}"
            error_log "Failed_TZ ${DATE_ERR_MSG} <- $LINENO of $PROGNAME"
            exit 0
        fi
        if ! remove_schedule; then
            ### need to update active.status
            exit 0 ### $RSCHED_ERROR
        fi
        ;;
    "--warnings")
        shift
        list_warnings $*
        if [ ! -e $LOGDIR/warnings.list ]; then
           echo "No optional components"
        else
        cat $LOGDIR/warnings.list
        $RM -f $LOGDIR/warnings.list
        fi
        ;;
    "--hist")
        shift
        if [ -e $PATCH_HISTORY ]; then
            cat $PATCH_HISTORY
        fi
        ;;
    "--help") 
        shift
        usage "Basic Usage"
        ;;
    "--errors")
        shift
        errors $*
        ;;
    "--status")
        read_status $LOGDIR/active.status
        ;;
    "--setinprogress")
        set_in_progress
        ;;
    "--files")
        shift
        get_umd_tag_value "$LOGDIR" $1.${ARCH}.umd PACKAGE _files_list
        /bin/cat /nn/patches/info/$1.${ARCH}.umd.rpms
        ;;
    "--hascomponents")
        shift
        #return 0 if components, otherwise return 1
        _component_list=
        get_umd_tag_value $LOGDIR $1-$2.${ARCH}.umd COMPONENT _component_list
        if [ ! "X$_component_list" == "X" ]; then
           exit 0
        else
           exit 1
        fi
        ;;
    "--components")
        shift
        #return a list of optional components
        _component_listo=
        get_umd_tag_value $LOGDIR $1-$2.${ARCH}.umd COMPONENT _component_list
		_componet_list=`echo $_component_list | sed -e 's/  */ /g'`
		_component_list=`echo $_component_list | sed -e 's/ /\n/g'`
        if [ ! "X$_component_list" == "X" ]; then
           echo "$_component_list" >$LOGDIR/$1-$2.${ARCH}.umd.opts
           echo "$_component_list"
        else
           echo "No optional components"
        fi
        ;;
    "-l") 
        shift
           _warnings=
           _details=
           if [ ! -f /nn/patches/info/readme/Warnings-$1.txt ] && [ ! -f /nn/patches/info/readme/Readme-$1.txt ]; then
              echo "No details available"
           fi
           if [ -f /nn/patches/info/readme/Readme-$1.txt ]; then
              /bin/cat /nn/patches/info/readme/Readme-$1.txt
           fi
           if [ -f /nn/patches/info/readme/Warnings-$1.txt ]; then
              /bin/cat /nn/patches/info/readme/Warnings-$1.txt
           fi
           ;; 
    "-d")
        Build_Date=`$RPM_BIN -q system-release --queryformat "%{INSTALLTIME:date} \n"`
        echo $Build_Date
        ;;
    "-v")
        Release=`$RPM_BIN -q system-release --queryformat "%{version} \n"`
        echo $Release
        ;;
    "--test")
        shift
        _args=$*
        if [ -n "$_args" ]; then
            if ! valid_date; then
                write_status $LOGDIR/active.status "Failed_TZ ${DATE_ERR_MSG}"
                error_log "Failed_TZ ${DATE_ERR_MSG} <- $LINENO of $PROGNAME"
                exit 0
            fi
            echo $1 > /nn/patches/info/active
            $RM -f $LOGDIR/*.status
            optional_selections $*
        fi
        ;;
esac


exit 0

