#! /usr/bin/sh
#
# ident	"%Z%%M%	%I%	%E% SMI"
#
# Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# To debug this script, set the environmental variable DEBUG to 1.
# (e.g. un-comment the next line)
#DEBUG=1
#

THEARGS=$@

CheckZones()
{
    ZONENAME=`/usr/bin/zonename`
    if [ ${ZONENAME} != "global" ]; then
        echo "Update Manager is only supported in the global zone. Exiting..."
        logger -tupdatemanager -p2 "Non global zone not supported. zone: $ZONENAME. Exiting"
        exit 1
    fi
}

# Update Manager will only run in the global zone
CheckZones

##
#  set debug flag
##
while [ $# -gt 0 ]
do
    case "$1" in
        -debug)  DEBUG=1;;
    esac
    shift
done

# required by basic reg component
LD_LIBRARY_PATH="/usr/lib/breg:/usr/lib/dc"
export LD_LIBRARY_PATH

# ---- variables definition
#
SOFTWARE_UPDATE=.softwareupdate

# --- executables--------
#
CCR_EXEC=/usr/lib/cc-ccr/bin/ccr
JAVA_EXEC=/usr/bin/java
MKDIR_EXEC="/usr/bin/mkdir -p"

###
# ---- Check for negative assetid, if it is, replace leading "-" with "N".
###
checkNegAssetId() {
    GDIR=`echo $ASSETID | sed -e "s/^-/N/"`
    if [ $DEBUG ] ; then
        echo "here is the fixed name: $GDIR"
    fi
}

##
#  read the assetId.
##
ASSETID=`$CCR_EXEC -g cns.assetid`
if [ $DEBUG ] ; then
    echo $ASSETID,"|"
fi

##
# get the HOSTID
##
HOSTID=`/usr/bin/hostid`
if test $ASSETID ; then

   # if negative, replace '-' with 'N'
   GDIR=""
   checkNegAssetId
   if [ $DEBUG ] ; then
       echo "after checkNegAssetId(), gdir=$GDIR"
   fi

   HOMEDIR="$HOME/$SOFTWARE_UPDATE/$GDIR"
else
   HOMEDIR="$HOME/$SOFTWARE_UPDATE/$HOSTID"
fi

if [ $DEBUG ] ; then
   echo $HOMEDIR,"|"
fi

## 
# ----- if $HOME/.sofwareupdate/$GDIR or $HOSTID directory exists ---- 
## 
if [ -d "$HOMEDIR" ]; then
    if [ $DEBUG ] ; then
        echo $HOMEDIR is there, proceed to start Update Manager
    fi

## 
# ----- else $HOME/.sofwareupdate/$GDIR or $HOSTID directory DOES NOT exists ---- 
## 
else
    # create $HOME/.softwareupdate/$GDIR directory
    #
    if [ $DEBUG ] ; then 
        echo "$HOMEDIR is NOT there, create one."
    fi
    $MKDIR_EXEC $HOMEDIR

fi

# ---- start Update Manager ----------------------
#
if [ $DEBUG ] ; then 
    echo "start Update Manager"
fi

# adding -client option to workaround bug 6208545
$JAVA_EXEC -client -jar /usr/lib/patch/swupdate.jar $THEARGS

exit 0
