#!/bin/sh
#
# Copyright 03/21/05 Sun Microsystems, Inc. All Rights Reserved.
#
# pragma ident  "@(#)es-machine	1.14 05/03/21 Sun Microsystems"
#

# This function is typically called by es-device. The database must be
# running.

print_usage() {
    echolog ""
    echolog "$PROGNAME -a machine-family [license-family license-weights]\n"
    echolog "$PROGNAME -d machine-family\n"
    echolog ""
}

###############################################
#
#   Main entry point
#
#
BASEDIR=`/usr/bin/pkgparam SUNWescom BASEDIR`
SCRIPT_DIR=${BASEDIR}/SUNWsymon/sbin    

. ${SCRIPT_DIR}/es-common.sh

set_basedir
set_db_env
create_temp_directory

PROGNAME=$0; export PROGNAME
SQLPLUS=$ORACLE_HOME/bin/sqlplus

if [ $# -le 1 ] ; then
    print_usage
    exit
fi
while getopts a:d: OPT
do 
   case $OPT in 
        a)
	   machinetype="null"
           machineweight="null"
           machinename="$OPTARG"

	   if [ $# -eq 4 ] ; then
	       machinetype=$3
	       machineweight=$4
	   elif [ $# -ne 2 ] ; then
	       print_usage
	       exit 1
	   fi

	   operation="add"
	   ;;
	d)
           machinename="$OPTARG"
	   operation="delete"
	   ;;
	\?)
	   print_usage
	   exit 1
	   ;;
   esac
done

if [ $operation = "add" ] ; then

    check=`echo $machineweight | /usr/bin/grep - |/usr/bin/wc -l`
    if [ $check -eq 1 ] ; then
       echolog "Negative license weight values are not allowed."
       exit 1
    fi
fi

if [ "$ES_DEVICE_DB_SYNC" = "lazy" ]; then
	set_xput 
	ServerName=`$XGET ${VARDIR}/domain-config.x agent.agentServer`
	tmp_dir=$VAROPTDIR/install
	addon_tmp_sql=$tmp_dir/addon_tmp_sql.$ServerName
else
        
	. ${BASEDIR}/lib/sbin/db-common.sh
	. $BASEDIR/db/cfg/dbadmin.cfg 
	tmpfile=$TMP_DIR/machine.$$ 
	/usr/bin/rm -f $tmpfile 
fi

if [ $operation = "add" ] ; then

    if [ $machinetype != "null" ] ; then
        sqlstring="sp_add_licensable_host_type('$machinename','$machinetype','$machineweight')"

	if [ "$ES_DEVICE_DB_SYNC" = "lazy" ]; then
	        $CMD_ECHO $sqlstring >> $addon_tmp_sql
	else
		db_runProc "$sqlstring" $SUNMC_USER $SUNMC_USER_PWD $tmpfile
		sql_retcode=$?
	fi
        
    else
        sqlstring="sp_add_licensable_host_type('$machinename',null,null)"
	if [ "$ES_DEVICE_DB_SYNC" = "lazy" ]; then
        	$CMD_ECHO $sqlstring >> $addon_tmp_sql
	else
		db_runProc "$sqlstring" $SUNMC_USER $SUNMC_USER_PWD $tmpfile
		sql_retcode=$?
	fi
    fi
else
    # delete
    sqlstring="sp_delete_machine_family('$machinename')"
	if [ "$ES_DEVICE_DB_SYNC" = "lazy" ]; then
        $CMD_ECHO $sqlstring >> $addon_tmp_sql
	else
        db_runProc "$sqlstring" $SUNMC_USER $SUNMC_USER_PWD $tmpfile
	sql_retcode=$?
	fi
fi

if [ "$ES_DEVICE_DB_SYNC" = "lazy" ]; then
	exit 0
else
	/usr/bin/rm -f $tmpfile

	if [ $sql_retcode -eq 0 ] ; then
    		exit 0 
	else
    		echolog "es-machine failed"
    		exit 1 
	fi
fi 
