#!/bin/sh

# Start the server part of the PHP/Java Bridge.  This script will be
# called by when the php-java-bridge service is started.

LANG_SYSTEM="${LANG-en_US.UTF-8}"
LANG=C
inst=user

# do some magic to avoid loading broken libraries from local
# installations if we are installed in one of the system directories.
instdir=`dirname $0`
case $instdir in
    /usr/bin|/usr/sbin|/bin|/sbin)
    inst=sys
    PATH=/sbin:/bin:/usr/sbin:/usr/bin:$PATH:
    LD_LIBRARY_PATH=/lib:/usr/lib:$LD_LIBRARY_PATH
    export PATH LD_LIBRARY_PATH
esac

# save the PID of the PHP/Java Bridge 
PID=/var/run/php-java-bridge.pid_test
(echo $$ >${PID}) >/dev/null 2>/dev/null
if test -w ${PID} && test $$ = `cat ${PID}` && rm -f ${PID}
then 
    PID=/var/run/php-java-bridge.pid
else 
    PID=/tmp/php-java-bridge.pid 
fi

# if called with non-zero args, invoke
if test $# != 0; then
  pid=${PID}
  log=/var/log/php-java-bridge
  if test "$inst" = "user"; then
      log=/tmp/php-java-bridge
  fi

  trap 'kill `cat ${pid}.[0-9]`; rm -f $pid' 2 15
  ext=$1; shift
  eval $1; shift
  eval $1; shift
  export JAVA_HOME LD_LIBRARY_PATH
  java="${ext}/RunJavaBridge"
  LANG="$LANG_SYSTEM" 
  unset LC_ALL
  $java "$@" &
  echo $! >$pid
  wait
  rm -f $pid.[0-9];
  exit 0
fi

# called with zero args, construct args
echo "<?php phpinfo();?>" | php 2>/dev/null >/tmp/phpinfo.$$
  
if fgrep java /tmp/phpinfo.$$ |
     sed 's/<[/a-z ="0-9]*>//g' |
     grep "java support.*Enabled" >/dev/null
then true;
else
 echo "Error: PHP/Java Bridge module not installed (see file /tmp/phpinfo.$$)." >&2; exit 1
fi

if  fgrep java /tmp/phpinfo.$$ |
    sed 's/<[/a-z ="0-9]*>//g' | 
    grep 'java status.*not running' >/dev/null
then 
    true
else
    if test -s $PID; then
	echo "PHP/Java Bridge already running with pid `cat $PID`" >&2
	rm -f /tmp/phpinfo.$$	
	exit 2;
    else
	echo "Error: java.socketname option not set in php .ini file, see output of phpinfo()." >&2
	exit 3;
    fi
fi

cmd=`fgrep java /tmp/phpinfo.$$ |
     sed 's/<[/a-z ="0-9]*>//g' | 
     sed -n '/^.*java command[^A-Z]*/s///p'`

ext=`fgrep extension_dir /tmp/phpinfo.$$ | head -1 |
     sed 's/<[TtRr][/a-z ="0-9]*>/ => /g' | 
     sed 's/<[/a-z ="0-9]*>//g' | 
     sed 's/^.*=> //'`

rm -f /tmp/phpinfo.$$
echo Starting java with the command: "$cmd"

# invoke
LANG="$LANG_SYSTEM"
if test "$inst" = "sys"; then
 # preserve name for status command
 /bin/sh -c "$0 $ext $cmd"         >/dev/null 2>/dev/null </dev/null&
else
 /bin/sh -c "/bin/sh $0 $ext $cmd" >/dev/null 2>/dev/null </dev/null&
fi
