#!/bin/sh
#############################################################################
# Copyright (C)2004-2005, Sun Microsystems Inc. All rights reserved.
# Use is subject to license terms.
#
# Name: create_crontab_entry
# Description: Common shell function to create crontab entries for the specified user.

# pragma ident 
##############################################################################

log="echo"

if [ $# -ne 4 ] ; then
    echo "Usage : `basename $0` <user> <entry> <service_name> <component_name>" 
    exit 1
fi

user="$1"
entry="$2"
service_name="$3"
component_name="$4"

#
# Validate the service and component for registration with the framework.
#
if [ ! -d "/usr/lib/cc-cfw/${service_name}" ] || [ ! -d "/usr/lib/cc-cfw/${service_name}/${component_name}" ]; then
    $log "ERROR : Either ${service_name}, or ${component_name} are not properly registered with the framework."
    exit 1
fi

tmp_dir="/tmp"
# a tmp file for crontab entries
tmp_crontab="$tmp_dir/tmp_crontab.$$"

# see if a crontab exists for the root
crontab_file="/var/spool/cron/crontabs/$user"
if [ -f $crontab_file ] ; then
	# read the existing crontab into a file
	crontab -l $user > $tmp_crontab
	if [ $? -ne 0 ] ; then
		echo "ERROR: could not get crontab for $user"
		#rm -rf $tmp_dir
		exit 1
	fi
else
	# create an empty tmp_crontab
	touch $tmp_crontab
fi

# is there an existing entry? If so, the component is already enabled.  Do not reenable it.
fgrep "$entry" $tmp_crontab > /dev/null
if [ $? -eq 0 ] ; then
	echo "WARNING: $component_name already enabled.  Not making any changes to the crontab"
	rm -rf $tmp_crontab
	exit 0
fi

echo "$entry" >> $tmp_crontab 

echo "Updating crontab for ${user}."
su $user -c "crontab < $tmp_crontab"

if [ $? -ne 0 ] ; then
    echo "ERROR: crontab could not be updated with an entry for the Inventory agent" 
    rm -rf $tmp_crontab
    exit 1
fi

# remove the cron file
rm -rf $tmp_crontab


### load the ENUM file ##
### Get the int values of the enabled status here.. ###
enum_file=/usr/lib/cc-cfw/framework/lib/status_enum
if [ -f $enum_file ] ; then
    . $enum_file
else
    $log status_enum interface not found. 
    exit 1
fi

 `/usr/lib/cc-cfw/framework/lib/get_interface SET_COMPONENT_STATUS` $service_name $component_name $ENABLE_STATUS_VALUE
