#!/bin/sh

# Quote each argument as a single-quoted token for safe tcsh -c command assembly.
quote_args_for_tcsh() {
  quoted_args=
  for arg in "$@"; do
    esc=$(printf "%s" "$arg" | sed "s/'/'\\\\''/g")
    quoted_args="$quoted_args '$esc'"
  done
  printf "%s" "$quoted_args"
}

# Save the original working directory
ORIG_DIR=$(pwd)
# Change to the directory of the script (scripts/) and then to its parent (project root)
cd "$(dirname "$0")/.."

jarFile="bin/CtmSaasMigrationTool-ctmconvert-jar-with-dependencies.jar"
fipsJar1="${HOME}/ctm_em/classes/emapicli/bc-fips-1.0.1.jar"
fipsJar2="${HOME}/ctm_em/classes/emapicli/bc-fips-1.0.2.jar"
fipsJar3="${HOME}/ctm_em/classes/emapicli/bc-fips-1.0.2.5.jar"
ctmemInfraJar="${HOME}/ctm_em/classes/infra-9.0.jar"
ctmemCommonJar="${HOME}/ctm_em/classes/common-9.0.jar"
ctmemContractsJar="${HOME}/ctm_em/classes/contracts-9.0.jar"
ctmemSecurityJar="${HOME}/ctm_em/classes/security-9.0.jar"
ctmemConfigurationJar="${HOME}/ctm_em/classes/commons-configuration2-2.12.0.jar"
ctmemTextJar="${HOME}/ctm_em/classes/commons-text-1.13.1.jar"

JAVA="./JRE/jre_64/bin/java"
JAVA_CP=".:${fipsJar1}:${fipsJar2}:${fipsJar3}:${ctmemInfraJar}:${ctmemCommonJar}:${ctmemContractsJar}:${ctmemSecurityJar}:${ctmemConfigurationJar}:${ctmemTextJar}:${jarFile}"

export EM_HOME=${HOME}/ctm_em
if [ ! -f "${jarFile}" ]; then
  echo "The file Control-M Saas Migration jar file ${jarFile} was not found"
  cd "$ORIG_DIR"
  exit 1
fi

tcshInstalled=$(em tcsh -c "echo test")
if [ "$tcshInstalled" = "test" ]; then
  quoted_args=$(quote_args_for_tcsh "$@")
  em tcsh -c "${JAVA} -Dorg.apache.poi.ss.ignoreMissingFontSystem=true -Xmx8G -cp ${JAVA_CP} com.bmc.ctmconvert.onequalify.AgentsScopingMainKt ${quoted_args}"
  cd "$ORIG_DIR"
  exit $?
fi

"${JAVA}" -Dorg.apache.poi.ss.ignoreMissingFontSystem=true -Xmx8G -cp "${JAVA_CP}" com.bmc.ctmconvert.onequalify.AgentsScopingMainKt "$@"
cd "$ORIG_DIR"
