#!/bin/bash
######################################################################################
#
# This script is used for testing the loading of a NeXtMidas default debug flag.
#
# Author: Zachary Matthews
# Since:  NeXtMidas 4.1.4
#
######################################################################################

# Check if NMROOT is defined
if [[ -z "${NMROOT}" ]]; then
  echo "WARNING: NMROOT is not defined"
  exit 1
fi

# Check if JAVAHOME is defined
if [[ -z "${JAVA_HOME}" ]]; then
  echo "WARNING: JAVA_HOME is not defined"
  exit 1
fi

# Check if midas_default_debug.txt exists
midasDefaultDebugFile=${NMROOT}/nxm/sys/cfg/midas_default_debug.txt
if [[ ! -f ${midasDefaultDebugFile} ]]; then
  echo "WARNING: ${midasDefaultDebugFile} not found"
  exit 1
fi

# Read the debug flag from midas_default_debug.txt
debugFlagOriginal=""
while IFS= read -r line
do
  if [[ ${line} != \!* ]] && [[ ${line} != \#* ]]; then
    debugFlagOriginal=${line}
    break
  fi
done < "${midasDefaultDebugFile}"

if [[ "${debugFlagOriginal}" == "" ]]; then
  echo "WARNING: ${midasDefaultDebugFile} debug flag not found"
  exit 1
fi

# Run NeXtMidas tests
export NM_STARTUP_MACRO=${NMROOT}/nxm/sys/test/bad_startup.mm

debugFlagZeros="0x000"
sed -i "s/${debugFlagOriginal}/${debugFlagZeros}/g" ${midasDefaultDebugFile} 
source ${NMROOT}/os/unix/nmstart.sh
source ${NMROOT}/os/unix/nmend.sh

sed -i "s/${debugFlagZeros}/${debugFlagOriginal}/g" ${midasDefaultDebugFile} 
source ${NMROOT}/os/unix/nmstart.sh
source ${NMROOT}/os/unix/nmend.sh
