#!/bin/ksh 

###############################################
# Sourcing macros
DIRNAME=/usr/bin/dirname
. `$DIRNAME $0`/../lib/psmacros
###############################################

###############################################
# Defines
###############################################

PS_STATE_FILE="$PS_CONFIG_DIR//PSConfig.properties"
PS_PKGINFO_FILE="/var/sadm/pkg/SUNWpscfg/pkginfo"

###############################################
# Get configuration from file
###############################################
GrabConfig() {
  local FILE=$1
  local KEY=$2
  local SEPARATOR=$3

  if [ -f $FILE ]; then
    ANSWER=`$GREP "^$KEY$SEPARATOR" $FILE | $UNIQ | $SED -e "s/$KEY$SEPARATOR//"`
  else 
    ANSWER=""
  fi
}

###############################################
# Main
###############################################

if [ -f $PS_STATE_FILE ]; then
  GrabConfig $PS_STATE_FILE "BASEDIR" "="
  PS_BASEDIR=$ANSWER
else
  if [ "$OSTYPE" = "SunOS" ]; then
    GrabConfig $PS_PKGINFO_FILE "BASEDIR" "="
    PS_BASEDIR=$ANSWER
  fi
  if [ "$OSTYPE" = "Linux" ]; then
    CONFIG_RPM="sun-portal-configurator"
    /bin/rpm -q --quiet $CONFIG_RPM
    if [ $? -eq 0 ]; then
      ANSWER=`/bin/rpm -q --queryformat "%{INSTALLPREFIX}" $CONFIG_RPM`
      PS_BASEDIR=$ANSWER
    fi
  fi
fi
if [ "$PS_BASEDIR" = "" ]; then
  $ECHO "Error: Cannot determine PS_BASEDIR. $BELL_CHAR"
  exit 1
fi

VALID_JDK_DIR=""
JDK_DIRS="${JAVA_HOME} /usr/j2se /usr/java"
for DIR in $JDK_DIRS; do
  if [ -x $DIR/bin/java ]; then
    VALID_JDK_DIR=$DIR
    break
  fi
done
if [ "$VALID_JDK_DIR" = "" ]; then
  $ECHO "Could not find java."
  $ECHO "Please set JAVA_HOME to a JDK installed on this machine."
  exit 1
fi

set -A JAVA_SYSTEM_PROPERTIES
set -A ARGS
for OPT in "$@"; do
  DOPT=${OPT#-D}
  if [ ${#DOPT} -gt 0 ] && [ "$DOPT" != "$OPT" ]; then
    JAVA_SYSTEM_PROPERTIES[${#JAVA_SYSTEM_PROPERTIES[*]}]="$OPT"
  else
    ARGS[${#ARGS[*]}]="$OPT"
  fi
done

if [ -z ${LD_LIBRARY_PATH} ]; then
  LD_LIBRARY_PATH=$PS_BASEDIR/$PS_PRODUCT_DIR/lib
else
  LD_LIBRARY_PATH=$PS_BASEDIR/$PS_PRODUCT_DIR/lib:${LD_LIBRARY_PATH}
fi
export LD_LIBRARY_PATH

$VALID_JDK_DIR/bin/java -Xms64m -Xmx256m -classpath $PS_BASEDIR/$PS_PRODUCT_DIR/lib:$PS_BASEDIR/$PS_PRODUCT_DIR/lib/config.jar -Djava.library.path=$PS_BASEDIR/$PS_PRODUCT_DIR/lib -DPS_CONFIG_DEBUG=y ${JAVA_SYSTEM_PROPERTIES[@]} configurator ${ARGS[@]}
exit $?
