#!/bin/sh
#
# File:    es-add-addon-modules
# Author:  Eric Ch'ng
#
# Copyright 05/16/01 Sun Microsystems, Inc. All Rights Reserved.
# pragma ident  "@(#)es-add-addon-modules	1.4 01/05/16 Sun Microsystems"

# Procedure that performs the database addition
#
# Input :
#  $1 = modulename
#  $2 = moduleversion
# e.g. - Module1    3.0
# e.g. - Module2    1.0
addModule() {
    modulename=$1
    versionname=$2
    if [ -n "$modulename" -a -n "$versionname" ]; then
	sqlstring="call sp_module_add('$modulename','$versionname','Basic Pack');"
	result=`echo $sqlstring | $ORACLE_HOME/bin/sqlplus sunmc/sunmc`

	success=`echo $result | grep 'Call completed'`
	if [ -z "$success" ] ; then
	    echolog 'Cannot add DE addon module: $2 $3' "$modulename" "$versionname"
	fi
    else 
        echolog 'Invalid format modulename=$2, versionname=$3' "$modulename" "$versionname"
    fi
}

prog_base=`/usr/bin/basename $0`
common_cmd=`echo $0 | /usr/bin/sed s/$prog_base/es-common.sh/`
. $common_cmd

set_basedir
set_db_env

PROGNAME=$0

ESMODULES=$ESROOT/mdr/modules

TMPFILE=/tmp/`basename $0`.$$
> $TMPFILE

for COMP in `echo $ESMODULES | sed 's/:/ /g'`
do
    if [ `expr "$COMP" : '\/'` -eq 0 ]; then
	COMP=${ESROOT}/${COMP}
    fi

    DIR=${COMP}/cfg

    if [ -d "$DIR" ]; then
        if [ -d /var/opt/SUNWsymon/mdr/modules/cfg ] ; then
            for file in `find /var/opt/SUNWsymon/mdr/modules/cfg -name "*-m.x" -print`
            do
                basename=`basename $file "-m.x"`
                nawk '
                    $1 == "param:module" { m=$3 }
                    $1 == "param:version" { v=$3 }
                    END { printf("%s %s\n",m,v) }
                ' fn=$basename $file >> $TMPFILE
            done
        fi

	for file in `find $DIR -name "*-m.x" -print`
	do
	    basename=`basename $file "-m.x"`
	    nawk '
		$1 == "param:module" { m=$3 }
		$1 == "param:version" { v=$3 }
		END { printf("%s %s\n",m,v) }
	    ' fn=$basename $file >> $TMPFILE
	done
    fi
done

# Sort based on version, extract module names and remove unwanted modules
TMPFILE1=${TMPFILE}_1.$$
sort -rn -k 2,2 $TMPFILE | grep -v '^ *$' | grep -v metadata-manager > $TMPFILE1

count=0
for param in `cat $TMPFILE1`
do
    count=`expr $count + 1`
    if [ $count -eq 1 ] ; then # Module name
	modulename=$param
	continue
    fi
    if [ $count -eq 2 ] ; then
	count=0
	moduleversion=$param
	addModule $modulename $moduleversion
    fi
done

rm $TMPFILE
rm $TMPFILE1

exit 0
