#!/bin/bash

TMP_BUILD_DIR=".tmp"
SRC_FILES_LIST=".srcfiles"


## --------- common part to all tests : 
##           a) check a mpd is running
##           b) compile a source program

function check_mpiboot 
{
  echo "** Test ${0} : running ${PROG} ..." | tee -a $LOGFILE
  printf "** Is mpd running ?"
  mpistat >> $LOGFILE
  case $? in
      127) printf " No. And 'mpiboot' cannot be found. Check your path.\n"
           exit 1;;
        1) printf " No. Running it ...\n"
           mpiboot;;
        0) printf " Yes. Good.\n"
  esac;
}

#** 
#** compile () : compile (javac) a source code and exit if compilation fails
#** args:
#** $1 : full path to source code

function compile { 
  local shortname=`basename $1`
  printf "** Compiling ${shortname} ... " | tee -a $LOGFILE
  javac -d . $1  2>>$LOGFILE
  if [ $? -eq 0 ]; then
      printf "ok.\n" | tee -a $LOGFILE;
      return 0
  else
      printf "Failed.\n" | tee -a $LOGFILE;
      exit 1
  fi
}

#** 
#** list_directories () : recursively outputs the directories names 
#** args:
#** $1 : root dir from where to start 

function list_directories {
    list=`ls -F $1 |grep "/$"`
    if [ -n "$list" ]; then
       for i in $list
       do
          list_directories "$1/$i"
       done
    else
       echo "$1"
    fi   
    return $list;
}

#** 
#** list_directories () : recursively outputs the directories names 
#** args:
#** $1 : root dir from where to start 

function list_javas {
    #-- search recursively through directories beneath first
    list=`ls -F $1 |grep "/$"`
    if [ -n "$list" ]; then
       for i in $list
       do
          list_javas "$1/$i"
       done
    fi
    java_files="$1/*.java"
    for f in $java_files
    do
	 if [ -f $f ]; then
		   echo $f >> $SRC_FILES_LIST
	  fi
	 done

    return 
}

#** 
#** compile_jar () : compile all .java files found at any level underneath a given
#** directory and build the jar file accordingly to the directories structure.
#** args:
#** $1 : absolute path of root dir of files to compile  

function compile_jar { 
  if [ -z $1 ]; then
      printf "Internal error: compile_jar( ) called with no or empty argument.\n" | tee -a $LOGFILE;
      exit 1 
  fi
  echo "** Building in $PWD/$TMP_BUILD_DIR ..."
  mkdir $TMP_BUILD_DIR
  cp -r $1 $TMP_BUILD_DIR/
  cd $TMP_BUILD_DIR
  local rootdirshortname=`basename $1`
  list_javas ${rootdirshortname}
  if [ ! -f $SRC_FILES_LIST ]; then
	printf "Failed. No source files.\n" | tee -a $LOGFILE;
      exit 1
  else 
    src_files=`cat $SRC_FILES_LIST`
    for f in $src_files
    do
      compile $f
    done
  fi
  class_files=`cat  $SRC_FILES_LIST | sed -e "s/\.java/\.class/g"` 
  nb_class_files="`echo $class_files | wc -l`"
  echo "** Packing $nb_class_files into  ${rootdirshortname}.jar" 
  jar cvf ../${rootdirshortname}.jar ${class_files} >>  $LOGFILE
  cd ..
  echo "** Cleanup: removing $PWD/$TMP_BUILD_DIR ..."
  rm -rf $TMP_BUILD_DIR
}
