#!/bin/bash --

EXECDIRS="bin usr/bin usr/games"

set -e
. /usr/share/javahelper/jh_lib.sh

syntax()
{
   echo -e "Usage: jh_build [options] [<jar> <src>]"
   echo -e "Options:"
   echo -e "\t-h --help: show this text"
   echo -e "\t-V --version: show the version"
   echo -e "\t-q --quiet: don't print the build commands as they are executed"
   echo -e "\t-m<class> --main=<class>: Use this class as the main class"
   echo -e "\t-j<java-home> --java-home=<java-home>: Set the JAVA_HOME variable"
   echo -e "\t-o<javac-opts> --javacopts=<javac-opts>: Options to the Java compiler"
   echo -e "\t--clean: clean the build tree"
   echo -e "Environment Variables:"
   echo -e "\tJAVA_HOME: path to the JDK to use"
   echo -e "\tCLASSPATH: classpath to compile with and set in the manifest"
   echo -e "\tJH_JAR_EXTRA: extra files to be included in the jar"
   exit 1
}

ARGS="q quiet m main j java-home o javacopts clean" parseargs "$@"

if [ -n "`getarg j java-home`" ]; then
   JAVA_HOME="`getarg j java-home`"
elif [ -z "$JAVA_HOME" ]; then
   if [ -d /usr/lib/jvm/default-java ]; then
      JAVA_HOME=/usr/lib/jvm/default-java
   elif [ -d /usr/lib/jvm/java-gcj ]; then
      JAVA_HOME=/usr/lib/jvm/java-gcj
   else
      echo "Cannot find JAVA_HOME: aborting" 1>&2
      exit 1
   fi
fi
if [ -z "`getarg o javacopts`" ]; then
   JH_JAVAC_OPTS="`getarg o javacopts`"
else
   JH_JAVAC_OPTS="`getarg o javacopts`"
fi

if [ -n "`getarg clean`" ]; then
   rm -rf debian/_jh_manifest* debian/_jh_build*
   exit 0
fi

JAVAC="${JAVA_HOME}/bin/javac"
JAR=fastjar

if [ "$ARGC" -lt "2" ]; then
   syntax
fi

jarfile="${ARGV[0]}"
ext="`basename "$jarfile" .jar`"
srcdirs=
for (( i=1; i < "$ARGC"; i++ )); do
   srcdirs="$srcdirs ${ARGV[$i]}"
done

rm -f debian/_jh_manifest.$ext
touch debian/_jh_manifest.$ext
if [ -n "$CLASSPATH" ]; then
   echo -n "Class-Path: " >> debian/_jh_manifest.$ext
   echo $CLASSPATH | sed 's/:/ /g' >> debian/_jh_manifest.$ext
fi
if [ -n "`getarg m main`" ]; then
   echo "Main-Class: `getarg m main`" >> debian/_jh_manifest.$ext
   echo "Debian-Java-Home: $JAVA_HOME" >> debian/_jh_manifest.$ext
fi

mkdir -p debian/_jh_build.$ext
if [ -z "`getarg q quiet`" ]; then
   echo $JAVAC -cp $CLASSPATH:debian/_jh_build.$ext -d debian/_jh_build.$ext $JH_JAVAC_OPTS $srcdirs
fi
$JAVAC -cp $CLASSPATH:debian/_jh_build.$ext -d debian/_jh_build.$ext $JH_JAVAC_OPTS $srcdirs

touch "$jarfile"
jarpath="`realpath "$jarfile"`"

(
   cd debian/_jh_build.$ext;
   if [ -z "`getarg q quiet`" ]; then
      echo $JAR -c -f "$jarpath" -m ../_jh_manifest.$ext *   
   fi
   $JAR -c -f "$jarpath" -m ../_jh_manifest.$ext *
)
if [ -n "$JH_JAR_EXTRA" ]; then
   if [ -z "`getarg q quiet`" ]; then
      echo $JAR -u -f "$jarpath" -@
   fi
   echo "$JH_JAR_EXTRA" | sed 's/ /\n/g' | $JAR -u -f "$jarpath" -@ 
fi

