#!/bin/bash
set -e

# A java version of the generate.sh.
RPG_LANG="java"
echo $RPG_LANG
. $(dirname ${0})/internal-generate-shared.sh

# The first command line argument is the profile name.
check_profile ${1}

create_data_dir ${2}
echo Info: Generating into ${DATA_DIR:?}.

# Copy the precompiled part of the application to the generated directory.
# Equivalent of the module.a for C++.
JARS_DIR=${DATA_DIR:?}/jars

cp -R ${ROOT_DIR:?}/bin/javapart/common ${DATA_DIR:?}/
cp -R ${ROOT_DIR:?}/bin/javapart/modules ${DATA_DIR:?}/
cp -R ${ROOT_DIR:?}/bin/javapart/jars ${JARS_DIR:?}


# Use the standard preprocessor to generate the
# configuration file in the target directory.

CONFIG_FILE=${DATA_DIR:?}/generator.conf

cpp ${PROFILE_FILE:?} ${CONFIG_FILE:?}

# Also prepare the input files from all modules.
# Only one directory level is copied to avoid
# conflicts with versioning subdirectories.

mkdir "${DATA_DIR:?}/input"
for MODULEGROUP in ${ROOT_DIR:?}/src/modules/java/input/*
do
  cp -R ${MODULEGROUP:?} "${DATA_DIR:?}/input/"
done

# Prepare the template file that the generator uses.
TEMPLATE_DIR=${ROOT_DIR:?}/src/templates/java/rpg
cp ${TEMPLATE_DIR:?}/Worker.java ${DATA_DIR:?}/common/rpg/Worker.tpl

# Generate the application :-) ...

"${ROOT_DIR:?}/bin/rpg" --lang java "${CONFIG_FILE:?}" "${DATA_DIR:?}/common/rpg"
mv ${DATA_DIR:?}/common/rpg/main.xml ${DATA_DIR:?}/
mv ${DATA_DIR:?}/common/rpg/main.conf ${DATA_DIR:?}/

# Copy the rest of the program sources dependent on the filled template

cp ${TEMPLATE_DIR:?}/Main.java ${TEMPLATE_DIR:?}/WorkerManager.java ${TEMPLATE_DIR:?}/DummyMacros.java ${DATA_DIR:?}/common/rpg/

# Prepare the classpath parameter, includes a little clumsy definition of
# jar files used by the program. 

JAVA_CLASSPATH=${JARS_DIR:?}/jl1.0.jar:${JARS_DIR:?}/Tidy.jar:${JARS_DIR:?}/xom-1.1.jar
JAVA_CLASSPATH=${ROOT_DIR:?}/bin/javapart/common:${JAVA_CLASSPATH:?}

# Now compile the generated program.
javac -g -classpath ${JAVA_CLASSPATH:?} ${DATA_DIR:?}/common/rpg/Main.java ${DATA_DIR:?}/common/rpg/Worker.java ${DATA_DIR:?}/common/rpg/WorkerManager.java ${DATA_DIR:?}/common/rpg/DummyMacros.java

# And add a script to run the program

cp ${TEMPLATE_DIR:?}/run.sh ${DATA_DIR:?}/run.sh
chmod u+x ${DATA_DIR:?}/run.sh

html_tidy "${DATA_DIR}/main.xml"

parse_modules "${DATA_DIR}/main.xml" "${DATA_DIR}/module-classes.out"

echo Info: Done.
echo ${DATA_DIR}
