#!/bin/ksh -p
#
# ident "@(#)util_lib.ksh	1.2 05/05/18 SMI"
#
# Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

#
# CompareVersion()
#
# Description:
#     Compares the Version strings passed in.  The version string
#     must be in the form <n>.<n>[.<n>] where "n" is an integer.
#
# Parameters:
#     $1 and $2 the version strings to be compared
#
# Returns:
#     =0 if $1 is the same as $2
#     =1 if $1 is newer than $2
#     =2 if $2 is newer than $1
#
CompareVersion() {
    typeset r1=$1
    typeset v1
    typeset done1=false
    typeset r2=$2
    typeset v2
    typeset done2=false
    typeset res
    while /bin/true
    do
	v1=${r1%%.*}
	if [[ $v1 = $r1 ]]; then
	    r1="0"
	    done1=true
	else
	    r1=${r1#*.}
	fi
	v2=${r2%%.*}
	if [[ $v2 = $r2 ]]; then
	    r2="0"
	    done2=true
	else
	    r2=${r2#*.}
	fi
	let "res=v1-v2"
	if [[ $res -lt 0 ]]; then
	    # $1 < $2
	    return 2
	elif [[ $res -gt 0 ]]; then
	    # $1 > $2
	    return 1
	fi
	if $done1 && $done2; then
	    # no more substring to compare
	    # this means match
	    break
	fi
    done
    return 0
}

#
# UpdateParam()
#
# Description:
#     Updates the parameter in the file specified.  The parameters are
#     stored in the key=value pair.
#
# Parameters:
#     $1 - filename. The filename to be created under /etc/opt/SUNWut directory.
#	It must not contain ".." in the path and cannot be an absolute name.
#	It will create the file if the file specified does not exist.
#     $2 - the parameter key.  If the parameter is not already in the
#	file, a new entry for the parameter will be created.  Otherwise,
#	the existing entry will be replaced with the new value.
#     $3 - the parameter value.  If the value does not specified, the
#	entry will be removed.
#
# Returns:
#     =0 if successful
#     =1 if error
#
UpdateParam() {
    if [ $# -lt 2 ]; then
	return 1
    fi
    typeset file=$1
    typeset param=$2
    typeset value=$3
    typeset tmpfile=/var/opt/SUNWut/tmp/UpdateParam.$$

    # check the filename for "/" and ".."
    if expr "$file" : '.*/' > /dev/null ||
       expr "$file" : '.*\(\.\.\).*' > /dev/null; then
	return 1
    fi
    fpfile=/etc/opt/SUNWut/$file
    if [ ! -f $fpfile ]; then
	touch $tmpfile || return 1
    else
	grep -v "^${param}[ 	]*=" $fpfile > $tmpfile
    fi
    if [ -n "$value" ]; then
	print "${param}=${value}" >> $tmpfile
    fi
    if [ -s $tmpfile ]; then
	mv -f $tmpfile $fpfile
	chmod 644 $fpfile
    else
	/bin/rm -f $tmpfile $fpfile
    fi
    return 0
}
