#!/usr/bin/ksh -p

#
# ident "@(#)utagelog.ksh	1.5 04/09/16 SMI"
#
# Copyright 1999-2004 Sun Microsystems, Inc.  All rights reserved.
#

PATH=/bin:/usr/bin

#
# Globals
#

let top=0
stack[top]=""

#
# Save a value on top of the stack
#
#	push value
#
function _push {
	stack[ ((top=top+1)) ]=$1
}


#
# Remove a value from the top of the stack and store it in var
#
#	pop var
#
function _pop {
	v=${stack[top]}
	if [ $# -eq 1 ]; then eval "$1=$v"; fi
	unset stack[top]
	let "top = top - 1"
	if [ $top -lt 0 ]; then top=0; fi
}


#
# Print the contents of the stack
#
#	prstack
#
function _prstack {
	let n=1
	while (( n < $top ))
	do
		print -rn " ${stack[n]}"
		let n=n+1
	done
	print ""
}

# In configured mode set group to utadmin and permission to 640 on all log files
# In unconfigured mode set group to root and permission to 600 on all log files

changePerms () {
	ADMINGID=`$SUNWUTLIB/utadmingid`
	if [[ -f ${UTADMIN_CONF} ]]
	then
		chmod 640 $1
	else
		chmod 600 $1
	fi
	chgrp $ADMINGID $1
}


#
# Age a series of logfiles by renaming "filename" to "filename.0"
# and all files "filename.[0-9]*" to filename.$(($suffix+1)).
# This is done upto limit. If a file is to be renamed to filename.$(($limit+1)),
# it will be deleted.
#
#	agefile filename limit
#
# Example:
#	agefile /usr/adm/messages 3
# would do the following:
#	rm /usr/adm/messages.3
#	mv -f /usr/adm/messages.2 /usr/adm/messages.3
#	mv -f /usr/adm/messages.1 /usr/adm/messages.2
#	mv -f /usr/adm/messages /usr/adm/messages.1
#
function _agefile {
        filename=$1
        limit=$2

	prefix=${filename%.[0-9]*}	# directory and filename, but no suffix
	suffix=${filename##$prefix}	# just the suffix, if any
	suffix=${suffix##.}		# eliminate the '.'

	#
	# Calculate the new suffix
	#
	if [ -z "$suffix" ]
	then
		newsuffix=0
	else
		newsuffix=$(($suffix + 1))
	fi

	newfilename=$prefix.$newsuffix

	#
	# If the new file already exists, we recurse to deal with it
	#
	if [ -f $prefix.$newsuffix ]
	then
		_push "$filename"
		_push "$newsuffix"
		_push "$newfilename"

		_agefile $prefix.$newsuffix $limit 

		_pop newfilename
		_pop newsuffix
		_pop filename
	fi

	if [ $newsuffix -gt $limit ]
	then
		rm -f $filename
	else
		if [ -f $filename ]
		then
			mv $filename $prefix.$newsuffix
		fi
	fi

}
#Main
BASEDIR=/etc/opt/SUNWut/basedir
SUNWUT=`${BASEDIR}/lib/utprodinfo -r SUNWuto 2>/dev/null`/SUNWut
SUNWUTLIB=${SUNWUT}/lib
UTADMIN_CONF="/etc/opt/SUNWut/utadmin.conf"

_agefile $*
cp /dev/null $1
changePerms $1
