#! /bin/sh
#
# Perforce init script. $Revision: #1 $
#
# Author: Dan Steele
#
# Email: dsteele@perforce.com
#
# This script is meant to cleanly stop and start the Perforce server
# If you don't like the defaults put your own settings in /etc/perforce.conf
#
# If you have protection set you'll need to include a super user name
# and a valid ticket with a long expiry time (like Timeout: 99999999).
# add them to your config as P4USER and P4PASSWD (Put the ticket here).
# If you don't the 'stop' and 'restart' part of this script won't work.
#
#

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NAME=p4d
DAEMON=/usr/local/sbin/$NAME
CLIENT=/usr/local/bin/p4
SCRIPTNAME=/etc/init.d/Perforce
CONF=$NAME.conf

USER=perforce
P4ROOT=/home/perforce
P4PORT=1666
P4LOG=/var/log/p4log
P4JOURNAL=/var/lib/perforce/journal

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

. /etc/init.d/functions

#check that we're root.
[ `id -u` = 0 ] || exit 1

[ -f /etc/$CONF ] && . /etc/$CONF

export P4PORT P4ROOT P4LOG P4JOURNAL P4USER P4PASSWD P4DEBUG

# Run checks.
#

if [ ! -d $P4ROOT ]
then
	echo "$P4ROOT doesn't exist"
	exit 1
fi

if [ ! -f $P4JOURNAL ]
then
	JOURNALPATH=`echo $P4JOURNAL | sed 's/\(.*\)\/.*/\1/'`
	[ ! -d $JOURNALPATH ] && mkdir -p $JOURNALPATH
	touch $P4JOURNAL
fi

[ ! -f $P4LOG ] && touch $P4LOG

chown $USER.$USER $P4JOURNAL
chmod 700 $P4JOURNAL


chown $USER.$USER $P4LOG
chmod 700 $P4LOG

start() {
	echo -n $"Starting $NAME: "
	daemon su - $USER -c \'$DAEMON -d\'
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/perforce 
	return $RETVAL
}
stop() {
	echo -n $"Shuttting down $NAME: "
	$CLIENT admin stop
	RETVAL=$?	
	echo
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/perforce 
	return $RETVAL
}

restart() {
	stop
	return start
}

# See how we were called.
case "$1" in
    start)
	start
	;;
    stop)
	stop
	;;
    restart)
	restart
	;;
    *)
	echo $"Usage: $0 {start|stop|restart}"
	RETVAL=1
esac


exit $?