#! /usr/bin/sh

end() {
  exit
}

finish () {
  echo
  echo "========= End of building EJB Jolt example ========="
  echo
  end
}

completed() {
  echo
  echo "  The EJBean has been saved in"
  echo
  echo "   $WL_HOME/myserver/$JAR"
  echo
  echo "  To deploy the EJBean, either use the hot deploy feature of"
  echo "  the WebLogic Console to deploy the EJBean or add to the"
  echo "  \"weblogic.ejb.deploy\" property in the \"weblogic.properties\""
  echo "  file an entry to deploy the $JAR.jar."
  echo
  echo "  To run the client, follow the instructions in the"
  echo "  documentation for the example."
  echo
  finish
}

error() {
  echo
  echo "  An error has occurred. Error level: $1"
  cd $WORK_DIR
  finish
}

cleanup() {
  cd $WORK_DIR
  rm  -rf $TEMP
}

build() {
# Step 1: create directories

  if [ ! -d $TEMP ]
  then
     mkdir $TEMP
  fi
  if [ ! -d $EJB_CLIENT_CLASSES ]
  then
     mkdir -p $EJB_CLIENT_CLASSES
  fi


# Step 2: Compile Java classes

  javac -d $TEMP $EXAMPLE/*.java
  retval=$?
  if [ "$retval" -ne 0 ]; then
    error $retval
  fi

# Step 3: Copy classes to the clientclasses directory

  cp -R $EJB_TEMP/* $EJB_CLIENT_CLASSES
  retval=$?
  if [ "$retval" -ne 0 ]; then
    error $retval
  fi

# Step 4: Delete the Client code from the temp directory
#         and the Bean code from client directory

  rm $EJB_TEMP/$EXAMPLE/*Client*.class
  rm $EJB_CLIENT_CLASSES/$EXAMPLE/*Bean*.class
  retval=$?
  if [ "$retval" -ne 0 ]; then
    error $retval
  fi

# Step 5: Create a .ser file from the deployment descriptor

  java weblogic.ejb.utils.DDCreator -d $EJB_TEMP/$EXAMPLE -outputfile DD.ser $EXAMPLE/DeploymentDescriptor.txt
  retval=$?
  if [ "$retval" -ne 0 ]; then
    error $retval
  fi

# Step 6: Run ejbc on the DD.ser file, creating generated files

  java weblogic.ejbc -d $TEMP $EJB_TEMP/$EXAMPLE/DD.ser
  retval=$?
  if [ "$retval" -ne 0 ]; then
    error $retval
  fi

  cd $TEMP

# Step 7: Jar the EJBeans using the manifest file

  jar cmf ../$EJB_DIRECTORY/$EXAMPLE/manifest ../myserver/$JAR $EJB_DIRECTORY
  retval=$?
  if [ "$retval" -ne 0 ]; then
    error $retval
  fi
}

dependcheck() {
  if [ ! $CLIENT_CLASSES ]
  then
    echo
    echo   "Building the examples is dependent on setting certain variables"
    echo   "in your environment. Please source or dot command the setEnv.sh script"
    echo   "(found in the /weblogic directory) before running this script."
    finish
  fi
}

echo ""
echo "========= Start of building EJB Jolt example ========="
echo ""

WORK_DIR=`pwd`
JAR=jolt_ejb_bankapp.jar
EXAMPLE="bankapp"
EJB_DIRECTORY=examples/jolt/ejb
TEMP=../../../temp
EJB_TEMP=$TEMP/$EJB_DIRECTORY
EJB_CLIENT_CLASSES=$CLIENT_CLASSES/$EJB_DIRECTORY
CLASSPATH=$CLASSPATH:$TEMP;export CLASSPATH

# -- check dependencies --
dependcheck

# -- build EJBeans --
build

# -- cleanup --
cleanup
completed

exit 1
