#!/bin/sh
#
# ident "@(#)rc.skipkey	1.14	99/03/02 Sun Microsystems"
#
# Start/stop SKIP Key Manager for Solaris
#

SKIP_MODULES=/usr/kernel/misc
SKIP_LOG=/var/log/skipd.log
SKIP_INIT=/etc/.skipinit
SKIP_DB=/etc/skip//certdb
SKIP_BIN=/usr/sbin
SKIPD=$SKIP_BIN/skipd
SKIPKEY_CONF=/etc/skip//skipkey.conf
SCREEN_RC=/etc/init.d/sunscreen

# kill the named process(es)
#
killproc() {		
	pid=`/usr/bin/ps -e |
	     /usr/bin/grep $1 |
	     /usr/bin/sed -e 's/^  *//' -e 's/ .*//'`
	[ "$pid" != "" ] && kill $pid
}

# Check if we've just installed the packages
#
checkinstall()
{
	if [ -f $SKIP_INIT ]
	then
		if [ ! -f $SKIP_DB ]
		then
			#echo "Initializng SKIP certificates database..."
			$SKIP_BIN/skipdb -i 2>/dev/null
			$SKIP_BIN/skiplocal -i 2>/dev/null
			$SKIP_BIN/skipca -i 2>/dev/null
		fi
		rm -f $SKIP_INIT
	fi
}

case "$1" in

# Load all SKIP crypto modules and start the key manager daemon
#
'start')

	# Don't start the key manger if the conf directory does not exist
	#
	if [ ! -d "/etc/skip/" ]
	then
		echo "WARNING: abort - SKIP config directory does not exist."
		exit 1
	fi

	# Check for 64 bits mode
	#
	if `isalist | grep sparcv9 >/dev/null 2>&1` 
	then 
		arch="sparcv9"
	fi

	# Force loading of the keystore in case of SunScreen system
	#
	if [ -f $SCREEN_RC ]
	then
		/bin/echo "loading skip keystore."
		modload /kernel/drv/${arch}/skip_key >/dev/null 2>&1
	fi

	# Check that the SKIP keystore has been loaded
	#
	modinfo |grep skip_key >/dev/null 2>&1
	if [ $? != 0 ]
	then
		/bin/echo "WARNING: skip: keystore not loaded."
		exit 1
	fi

	# Verity that at least, one crypto module has been installed
	#
	ls ${SKIP_MODULES}/${arch} |grep skip >/dev/null 2>&1
	if [ $? != 0 ]
	then
		/bin/echo "WARNING: skip: no crypto modules found"
		exit 2
	else
		for module in ${SKIP_MODULES}/${arch}/skip* ; do
			modload $module
		done
	fi

	# Check if we need to initialize the SKIP certificate database
	#
	checkinstall

	# SKIP Kernel is OK - Can start the SKIP key manager
	#
	if [ -x $SKIPD ]; then

		# clean up old key manager log files
		#
		test -f $SKIP_LOG.2 && mv $SKIP_LOG.2 $SKIP_LOG.3
		test -f $SKIP_LOG.1 && mv $SKIP_LOG.1 $SKIP_LOG.2
		test -f $SKIP_LOG.0 && mv $SKIP_LOG.0 $SKIP_LOG.1
		test -f $SKIP_LOG   && mv $SKIP_LOG   $SKIP_LOG.0

		# start SKIP key manager
		#
		/bin/echo "starting skip key manager daemon\c"
		$SKIPD > $SKIP_LOG 2>&1 &
		/bin/echo "."
	fi

	# Check for a SKIP keystore configuration file
	#
	if [ -f $SKIPKEY_CONF ]
	then
		/bin/sh $SKIPKEY_CONF >/dev/null
	fi

	;;

# Stop the SKIP key manager daemon
#
'stop')
	killproc skipd
	/usr/sbin/modunload -i 0

	;;
*)
	/bin/echo "Usage: /etc/init.d/skipkey { start | stop }"
	;;
esac
