#!/bin/sh
#=================================================================
#
#       Name: build_trick
#
#   Synopsis: build_trick [option]
#      no option: creates build directory and compiles src/java
#                 to build directory
#                 creates distribution directory and builds trick.jar
#          clean: deletes the build and dist directory trees
#        javadoc: builds Trick java api documentation at docs/api
#       doccheck: runs Sun's doccheck tool and generates reports
#                 at docs/api/doccheck
#     clean_docs: deletes all files and folders in docs/api
#
#   Examples:   build_trick
#               build_trick clean
#               build_trick javadoc
#
#=================================================================

# Get the relative path to where this file is located
BUILD_TRICK_DIR=`dirname $0`

getabsPath() {
    ABSPATH=""
    if [ "`echo $@`" != "" ] ; then
        cwd=`pwd`
        TARGET=`ls -l $@ 2>/dev/null | sed -e 's/.*->\\s*//' `
        cd `dirname $TARGET 2>/dev/null`
        ABSPATH="`pwd -P`/`basename $TARGET 2>/dev/null`"
        cd $cwd
    fi
    echo "$ABSPATH"  #return value
}

printJavaHomeError() {
    echo "[31mJAVA_HOME environment variable is not set correctly[00m"
    echo "[31mJAVA_HOME must be set to a valid jdk directory (not jre)[00m"
    JAVAC=`readlink -f \`which javac 2>/dev/null\` 2>/dev/null `
    # when "readlink -f" command doesn't work, try to find javac manually
    if [ "$JAVAC" = "" ] ; then
        JAVAC=`getabsPath \`which javac 2>/dev/null\` `
    fi
    # the jdk directory should be 2 levels up from the javac path
    JDK_DIR=`dirname \`dirname $JAVAC 2>/dev/null\` 2>/dev/null `
    if [ "$JDK_DIR" != "" ] && [ "$JDK_DIR" != "$JAVA_HOME" ] ; then
        echo "try setting JAVA_HOME to: \"$JDK_DIR\""
    fi
    exit -1
}

setJavaCmd(){
    JAVACMD="${JAVA_HOME}/bin/java"
    if [ `uname -s` = "Darwin" ] && [ ! -e "${JAVA_HOME}/bin/java" ] ; then
        JAVACMD="${JAVA_HOME}/Commands/java"
    fi
    echo `java -version`
}

# Test if JAVA_HOME is good.
if [ "$JAVA_HOME" = "" ] ||
   ( [ ! -e "${JAVA_HOME}/bin/java" ] &&
     [ ! -e "${JAVA_HOME}/Commands/java" ] ) ; then
    printJavaHomeError
else
    setJavaCmd
fi

# Test if we are using a 64-bit java executable on a 32-bit computer
WRONG_ARCHITECTURE=`echo \`$JAVACMD? -version 2>&1\` | grep \
                -e 'cannot execute' \
                -e 'format error' \
                -e 'Wrong Architecture' `
if [ ${#WRONG_ARCHITECTURE} -ne 0 ]  ; then
    echo "Error: Cannot run 64 bit java in 32 bit mode."
    printJavaHomeError
fi


# Run "Ant" via the java command to build Java applications.
# When run, Ant looks for a build.xml file in the current directory and
# uses that file as the build file. If no target (i.e. $1) is specified
# by the user, Ant runs the target specified in the 'default' attribute
# of the <project> tag. To find out what targets are available for use,
# search for "<target name=" in the build file.
ANTCALL="$JAVACMD \
         -classpath ${BUILD_TRICK_DIR}:${TRICK_HOME}/bin/java/lib/ant-launcher.jar \
          org.apache.tools.ant.launch.Launcher \
         -emacs \
         -keep-going \
         -buildfile ${BUILD_TRICK_DIR}/build.xml"

if [ "$1" = "" ] ; then
    # No option given; build.xml will build the default target
    echo
    echo "[36mBuilding Trick GUIs...[00m"
    # Execute ${ANTCALL} and save the standard output
    STDOUT=`$ANTCALL 2>&1` # Also redirect std error msgs to standard output

    # Viewing "BUILD SUCCESSFUL" while running compile_trick may be confusing.
    # Replace/remove "BUILD SUCCESSFUL" / "BUILD FAILED" / "Total time" from stdout.
    OUTPUT=`echo "$STDOUT" \
                | sed -e 's/BUILD FAILED/[31mJava build failed[00m/g' \
                | sed -e 's/BUILD SUCCESSFUL/[32mJava build successful[00m/g' \
                | sed -e 's/ warning/[33m warning[00m/g' \
                | sed -e 's/Total time/Java build total time/g'  `
    # Send new output to the screen.
    echo "${OUTPUT}" # use quotes to preserve embedded newlines characters

    # Test for errors...
    ERRORS=`echo $OUTPUT | grep "error"`
    if [ ${#ERRORS} = 0 ] ; then
        echo "[32m=== Trick GUI compilation complete ===[00m"
        date
    fi
elif [ "$1" = "-help" ] || [ "$1" = "-h" ] || \
     [ "$1" = "help" ] || [ "$1" = "--help" ] ; then
    # Note "-help" and "-h" are reserved for Ant
    if [ "$1" = "-help" ] || [ "$1" = "-h" ] ; then
        # Prepend ant Options before listing build_trick options
        $ANTCALL $1
        echo
    fi
    echo
    echo "build_trick [option]"
    echo "Options:"
    echo -e "   (no option)\t\t Builds the default target given in \"build.xml\""
    # Display every target name (+description) listed in the build file.
    grep "<target\ name=" ${BUILD_TRICK_DIR}/build.xml \
        | sed -e 's/\s*<target name=\s*"/   /g' \
        | sed -e 's/"\s*.*description=\s*"/ \t\t /g' -e 's/"\s*.*>//g'
    echo -e "   help, --help\t\t print this message"
else
    echo
    if [ "$1" = "clean" ] ; then
        echo 'Cleaning Trick GUIs...'
    fi
    $ANTCALL $1
fi
