#!/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:/usr/local/sbin:/usr/local/bin:$PATH:
    LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/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.log
  if test "$inst" = "user"; then
      log=/tmp/php-java-bridge.log
  fi

  trap 'kill `cat ${pid}`; rm -f ${pid}.old' 2 15
  ext=$1; shift
  while true; do
      case $1 in
	  [A-Z]*) eval $1; shift;;
	  *) break;;
      esac
  done
  export JAVA_HOME LD_LIBRARY_PATH
# Even if the user has set his own java.wrapper, we want to
# use our RunJavaBridge, because it carries the SEL
# javabridge_exec_t context (necessary for a domain transition).
# If the default wrapper is also RunJavaBridge, this means that 
# RunJavaBridge calls itself before it calls java. This is harmless.
  java="${ext}/RunJavaBridge"
  LANG="$LANG_SYSTEM" 
  unset LC_ALL
  if test -x ${java}; then
    $java "$@" >>$log 2>&1 &
  else
    "$@" >>$log 2>&1 &
  fi
  rm -f ${pid}.old; if test -s $pid; then mv $pid ${pid}.old; fi
  echo $! >$pid
  wait
  rm -f $pid; if test -s ${pid}.old; then mv ${pid}.old $pid; fi

  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

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
