#!/bin/sh
SCRIPT_PATH=`dirname $0`
FREEHEP_PATH=$SCRIPT_PATH/vectorgraphics
LOGFILE=/tmp/samurai-graph-$$.log

# check JDK_HOME environment
JDK_HOME_ENV=`env | grep JDK_HOME`
JAVA_HOME_ENV=`env | grep JAVA_HOME`
JAVAHOME_ENV=`env | grep JAVAHOME`
JAVA_PATH_ENV=`env | grep JAVA_PATH`
if [ -z $JDK_HOME_ENV ]; then
  if [ -z $JAVA_HOME_ENV ]; then
    if [ -z $JAVAHOME_ENV ]; then
      if [ -z $JAVA_PATH_ENV ]; then
        echo "Error : JDK_HOME or JAVA_HOME or JAVAHOME or JAVA_PATH does not defined"
        exit 1
      else
        JDK_HOME=$JAVA_PATH
      fi
    else
      JDK_HOME=$JAVAHOME
    fi    
  else
    JDK_HOME=$JAVA_HOME
  fi
fi

# change current directory to top directory of vectorgraphics libraries.
cd $FREEHEP_PATH
CURRENT_PATH=`pwd`
FREEHEP=$CURRENT_PATH

TOOLS_PATH=$CURRENT_PATH/../../tools
ANT_HOME=$TOOLS_PATH
ANT_OPTS=

# build depend jar files
FREEHEP_BUILDTOOLS_JAR=$FREEHEP/tools/freehep-buildtools.jar
ANT_JAR=$ANT_HOME/ant.jar
ANT_OPTIONAL_JAR=$ANT_HOME/ant-optional.jar
JUNIT_JAR=$TOOLS_PATH/junit.jar
JNLP_JAR=$TOOLS_PATH/jnlp.jar
JDK_TOOLS_JAR=$JDK_HOME/lib/tools.jar

# class path
CLASSPATH=$FREEHEP_BUILDTOOLS_JAR:$JUNIT_JAR:$ANT_JAR:$ANT_OPTIONAL_JAR:$JNLP_JAR:$JDK_TOOLS_JAR

# ant command
ANT="java -cp $CLASSPATH -Dant.home=\"$ANT_HOME\" $ANT_OPTS org.apache.tools.ant.Main"

DONEFILE=$CURRENT_PATH/../.build_vectorgraphics_done

JARFILES="base graphics2d graphicsio graphicsio-cgm graphicsio-emf graphicsio-gif graphicsio-java graphicsio-pdf graphicsio-ppm graphicsio-ps graphicsio-svg graphicsio-swf"

build_vectorgraphics () {
  if [ ! -f $DONEFILE ]; then
    for i in $JARFILES; do \
      echo -n "[vectorgraphics] cleating freehep-$i.jar ... "
      $ANT -Djar=$i > $LOGFILE 2>&1
      if [ $? != 0 ]; then
        echo error
        cat $LOGFILE
        rm -f $LOGFILE
        exit 1
      else
        echo done
      fi
    done
    touch $DONEFILE
    rm -f $LOGFILE
  fi
}

clean_vectorgraphics () {
  rm -f $DONEFILE
  echo -n "[vectorgraphics] deleting jar files ..."
  $ANT veryclean > $LOGFILE 2>&1
  if [ $? != 0 ]; then
    echo error
    cat $LOGFILE
    rm -f $LOGFILE
    exit 1
  else
    rm -f lib/freehep-version.txt
    rm -f $LOGFILE
    echo done
  fi
}

case "$1" in
rebuild)
  clean_vectorgraphics
  build_vectorgraphics
  ;;
build)
  build_vectorgraphics
  ;;
clean)
  clean_vectorgraphics
  ;;
*)
  echo "Usage: ${0##*/}: { build | rebuild | clean }" 2>&1
  exit 65
  ;;
esac

exit 0
