#!/bin/sh -e
#
#   /etc/init.d/p4d: start or stop perforce repository
#

#User
export P4USER=harry
#Repository
#export P4ROOT=/var/tmp/perforce
#export P4ROOT=$PWD
#Journal
#export P4JOURNAL=/var/tmp/perforce/journal
export P4JOURNAL=$P4ROOT/journal
#Server Executable
export P4D=$P4DROOT/p4d
#Admin tool
#export P4=/usr/local/sbin/p4
#Logfile
export P4LOG=$P4ROOT/errors
#LogLevel
export P4LOGLEVEL="-v server=1"
#Commandline options (fork, errorlog, ... see $P4D -h)
export P4DOPTIONS=" -d -p $P4DPORT"

PID=""

[ -x $P4D ] || exit 0
#buggy for too long pathes, but basename in conflict with client programs?
#P4PID=`ps -ef | grep $P4D | grep -v grep | awk '{ printf $2;}'`

case "$1" in
  start)
      echo  "Starting up: p4d"
      if [ -n "$P4PID" ]; then
        echo "$P4D is already running"
      else
        #killall p4d 
        $P4D $P4DOPTIONS -r $P4ROOT -J $P4JOURNAL -L $P4LOG $P4LOGLEVEL
      fi
    ;;
  stop)
      #$P4 admin stop
      #Hard, but works... without admin user
      killall p4d
      #echo  "Shutting down P4D"
      #P4PID=`ps -ef | grep $P4D | grep -v grep | awk '{ printf $2;}'`
      #if [ -z "$P4PID" ]; then
      #		#echo "$P4D may not run..."
#		exit 0
#      else
#		kill $P4PID
#      fi
    ;;
  restart|force-reload)
      echo "Not implemented"
      exit 1
      ;;
  *)
      echo "Usage: /etc/init.d/p4d {start|stop|restart|force-reload}"
      exit 1
    ;;
esac

exit 0