#!/bin/sh
umask 0027

#
# $Header: whdev/2.0/owb/shiphome/owb/bin/unix/ccastart /tahoelc/1 2009/11/17 20:09:39 jinghe Exp $
#
# ccastart  
#
# Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved. 
#
#    NAME
#      ccastart - Startup of OWB Control Center Agent
#
#    DESCRIPTION
#      This will startup OWB Control Center Agent. An optional argument to specify
#      the location for the OWB Control Center Agent console log. By default, the log file
#      will be placed in the admin directory.
#


DIR=`expr $0 : '\(.*\)/'`
if [ "x$DIR" = "x" ]; then
   DIR='.'
fi

# check whether Control Center Agent J2EE server is already running, we check port 23791
  port=`grep 'port=' $DIR/../../jrt/config/rmi.xml | sed -e 's/[^0-9]//g'`
  echo "Checking admin port: $port"
  if [ "x$port" = "x" ]
  then
    echo "Failed in getting the admin port, use 23791 instead"
    port="23791"
  fi

  if netstat -an | grep $port | grep -i listen
  then
    echo "Port $port is already in use"
    exit 1
  fi

# include OWB environment settings
. $DIR/owbenv

# setup log file path
LOG_FILE=$OWB_ADMIN_DIR/jrt.log
if [ "x$1" != "x" ]; then
  LOG_FILE=$1
fi
echo "OC4J log file at $LOG_FILE"

JRT_LOG_FILE=$OWB_JRT_RUN_HOME/log/jrt.log
echo "Control Center Agent log file at $JRT_LOG_FILE"

JRT_JVM_XOPTS="-Xverify:none -XX:MaxPermSize=128M -XX:+DisableExplicitGC"

echo  "Starting Control Center Agent... "
# Patch ascontrol icons
$JAVA_HOME/bin/java $JAVA64FLAG -Doracle.home=$OC4J_HOME -Doracle.j2ee.home=$OWB_JRT_RUN_HOME $JRT_JVM_XOPTS $OWB_JVM_OPTS -mx128M -classpath $OWB_HOME/owb/lib/int/jrt_client.jar oracle.wh.jrt.util.EMUpdater > $LOG_FILE 2>&1 

# Activate admin user on first invocation
if $JAVA_HOME/bin/java $JAVA64FLAG -Doracle.home=$OC4J_HOME -Doracle.j2ee.home=$OWB_JRT_RUN_HOME $JRT_JVM_XOPTS $OWB_JVM_OPTS -mx128M -classpath $OWB_HOME/owb/lib/int/jrt_client.jar:$OC4J_HOME/j2ee/home/jazn.jar oracle.wh.jrt.util.AdminTool
then
  echo ""
else
    exit 1
fi

# start OWB Control Center Agent J2EE server
$JAVA_HOME/bin/java $JAVA64FLAG -Doracle.home=$OC4J_HOME -Doracle.j2ee.home=$OWB_JRT_RUN_HOME -Dpython.path=$OWB_JRT_RUN_HOME/applications/jrt/jython_lib.zip:$OWB_JRT_RUN_HOME/applications/jrt/jython_owblib.jar $JRT_JVM_XOPTS $JRT_JVM_DOPTS $OWB_JVM_OPTS -mx128M -jar $OC4J_HOME/j2ee/home/oc4j.jar -config $OWB_JRT_RUN_HOME/config/server.xml >> $LOG_FILE 2>&1 &

# check startup status from log file
COUNT=0
while [ $COUNT -lt 60 ]; do
  if [ "x`tail -100l $LOG_FILE 2>&1 | egrep 'Oracle Containers .* initialized'`" != "x" ]; then
    echo "done"
    exit 0
  fi

  if [ "x`tail -100l $LOG_FILE 2>&1 | egrep 'Address already in use'`" != "x" ]; then
    echo "already started"
    exit 1
  fi

  if [ "x`tail -100l $LOG_FILE 2>&1 | egrep 'server exiting|startup failed'`" != "x" ]; then
    break
  fi

  sleep 3
  COUNT=`expr $COUNT + 1`
done

echo "failed, see log for details"
exit 1
