#!/bin/bash

# java runtime decompiler launch script

# JPackage Project <http://www.jpackage.org/>
# Source functions library
echo "Special jdk8 build of JRD. "
echo "You will most likely set agent manually to java-runtime-decompiler-jdk8/decompiler-agent8.jar"
echo "Normal, jdk11 JRD should be able to reuse jdk8 agent, but not the oposite"
echo "No one can guarantee the bytecode level of decompilers. You may need to download older versions from somewhere"

if [ "x$JAVA_HOME" = "x" ] ; then
  export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk
fi

. /usr/share/java-utils/java-functions

# identify directory tree
JRD=`java-runtime-decompiler`
CONF_HOME=$XDG_CONFIG_HOME


if  [ "$CONF_HOME" = "" ] ; then 
  CONF_HOME=$HOME/.config/$JRD

else
  CONF_HOME=$CONF_HOME/$JRD

fi

LOG_DIR=$CONF_HOME/logs

CONF_DIR=$CONF_HOME/conf

# create directory tree
PLUGIN_HOME=$CONF_HOME/plugins

mkdir -p $LOG_DIR

mkdir -p $CONF_DIR

mkdir -p $PLUGIN_HOME

: ${MAIN_CLASS:=org.jrd.backend.data.Main}

# set java and jvm arguments
export _prefer_jre=false
_set_java_home
set_jvm

# all dependencies must be on classpath
set_classpath byteman google-gson
CLASSPATH=$CLASSPATH:${JAVA_HOME}/lib/tools.jar:/usr/share/java/java-runtime-decompiler-jdk8/runtime-decompiler8.jar:/usr/share/java/java-runtime-decompiler-jdk8/decompiler-agent8.jar

# set path to agent automatically
AGENT="/usr/share/java/java-runtime-decompiler/decompiler-agent8.jar"
CONFIG_FILE=$CONF_DIR/config.cfg
AGENT_PREFIX="AGENT_PATH==="
AGENT_STRING=$AGENT_PREFIX$AGENT

# copy json wrappers information to home so the users can edit
CP_FILES="$(ls /etc/$JRD/plugins/*.json)"
for cpfile in $CP_FILES; do
    FILE_NAME="$(basename -- $cpfile)"
	if [ ! -e "$PLUGIN_HOME/$FILE_NAME" ]
	then
		cp $cpfile $PLUGIN_HOME
	else
		echo "Configuration files were not copied for $FILE_NAME - the existing configuration would be overwritten." >&2
	fi
done

# create config file and add agent default path
touch $CONFIG_FILE

if [ -e $AGENT ]
then
	if grep -Fxq $AGENT_STRING $CONFIG_FILE
	then
		echo "Default agent path is already set in $CONFIG_FILE. Skipping agent path setting." >&2
	elif grep -rq $AGENT_PREFIX $CONFIG_FILE
	then
		RESULT_OF_GREP="$(grep -rq $AGENT_PREFIX $CONFIG_FILE)"
		echo "Agent path is already set in $CONFIG_FILE as ${RESULT_OF_GREP}. Skipping agent path setting." >&2
	else
		echo  $AGENT_STRING >> $CONFIG_FILE

	fi
else
	echo "Agent was not found and agent path was not set correctly. This has to be done manually in the decompiler GUI, or set AGENT_PATH===path_to_agent_jar in the configuration file: $CONFIG_FILE" >&2
fi

export FLAGS="$FLAGS -Djdk.attach.allowAttachSelf=true"
jvm_run   "$@"
