#!/bin/sh

# set the current working dir as the PROJECT_HOME variable 

cygwin=false;
darwin=false;
freebsd=false;

case "`uname`" in
  CYGWIN*) cygwin=true ;;
  Darwin*) darwin=true
           if [ -z "$JAVA_HOME" ] ; then
             JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Home   
           fi
           ;;
  FreeBSD*) freebsd=true
	    if [ -z "$JAVA_HOME" ] ; then
	      JAVA_HOME=/usr/local/jdk1.4.2
	    fi
	    ;;
esac
export JAVA_HOME

if [ "$cygwin" = "true" ] ; then
  PROJECT_HOME=`cygpath -w "$PWD"`
else
  PROJECT_HOME=`pwd`
fi

# Try to determine the FORREST_HOME
if [ -z "$FORREST_HOME" ] ; then
  # Note: this piece of code is based on ant's shell script

  ## resolve links - $0 may be a link to ant's home
  PRG=$0
  progname=`basename $0`
  saveddir=`pwd`

  # need this for relative symlinks
  cd `dirname $PRG`

  while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '.*/.*' > /dev/null; then
  PRG="$link"
    else
  PRG="`dirname $PRG`/$link"
    fi
  done

  FORREST_HOME=`dirname "$PRG"`/..

  # make it fully qualified
  FORREST_HOME=`cd "$FORREST_HOME" && pwd`

  cd $saveddir
fi
export FORREST_HOME
  						
# Save old ANT_HOME
OLD_ANT_HOME="$ANT_HOME"
unset ANT_HOME

# ----- Set Up The Runtime Classpath ------------------------------------------

if [ "$cygwin" = "true" ] ; then
  S=';'
  FORREST_DOT_HOME=`cygpath -w "$FORREST_HOME"`
else
  S=':'
  FORREST_DOT_HOME=$FORREST_HOME
fi

# set the ant file to use
ANTFILE="$FORREST_DOT_HOME/forrest.build.xml"

CP="$CLASSPATH"
export CP
unset CLASSPATH

for i in $FORREST_HOME/lib/endorsed/*.jar; do
  if [ "$cygwin" = "true" ] ; then
    LIB=`cygpath -w $i`
  else
    LIB=$i
  fi

  CLASSPATH=$CLASSPATH$S$LIB
done

export CLASSPATH

echo "Apache Forrest.  Run 'forrest -projecthelp' to list options"
echo
"$FORREST_HOME/ant/bin/ant" -buildfile "$ANTFILE" -Dbasedir="$PROJECT_HOME" -Dproject.home="$PROJECT_HOME" -Dforrest.home="$FORREST_DOT_HOME" -emacs $@
RESULT=$?

# ---- Restore Classpath
unset CLASSPATH
CLASSPATH=$CP
export CLASSPATH

# ---- Restore ANT_HOME
# Restore old ANT_HOME
ANT_HOME="$OLD_ANT_HOME"
export ANT_HOME

exit $RESULT
