#! /bin/bash

confhelp() {
  echo ""
  echo "debug - script for MEGAlib";
  echo "(C) by Andreas Zoglauer"
  echo "";
  echo "Usage:";
  echo "    debug [Program] <arguments>";
  echo "";
  echo "Example:";
  echo "    debug mimrec -f MyFile.tra";
  echo "";
  echo "This script lauches a program with gdb/lldb (and if you have a known MEGAlib program, it recompiles first)"
  echo "";
}

# Test if an architecture is provided
if [ $# -lt 1 ] ; then
  echo " ";
  echo "Error: You must specify a program!";
  confhelp
  exit 1;
fi

# Test if help is requested:
case $1 in
-h|--help) 
  confhelp; 
  exit 0;;
esac

# Check if a debugger is installed
DEBUGGER=gdb
type ${DEBUGGER} >/dev/null 2>&1
if [ $? -ne 0 ]; then
  DEBUGGER=lldb
  type ${DEBUGGER} >/dev/null 2>&1
  if [ $? -ne 0 ]; then
    echo "ERROR: you must have either gdb or lldb installed"
    exit 1
  fi 
fi 


echo " "
echo "Starting debug ..."


# A. Retrieve all arguments
megadir=${MEGALIB}
currdir=`pwd`

program=$1
shift
args=""

while [ $# -gt 0 ] ; do
  args="${args} $1"
  shift
done

command -v ${program} >/dev/null 2>&1
programnotfound=$?
programpath=""
if [ ${programnotfound} -eq 0 ]; then
  programpath=`which ${program}`
  programpath=`dirname ${programpath}`
  echo "Program found in path: ${programpath}"
else
  echo "Program not found ... Assuming it is a not yet compiled MEGAlib program ..."
fi

recompile=0
if ( [ "${programpath}" == "" ] || [ "${programpath}" == "${MEGALIB}/bin" ] ); then
  recompile=1
fi

  

# B. Check for recompilation:

# switch into architectural dependent configurations
if [ ${recompile} -eq 1 ]; then 
  echo "Checking for recompilation of a MEGAlib program ..."
  cd ${megadir}

  case ${program} in
  geomega)
    make -f ${MEGALIB}/Makefile geo;;
  revan)
    make -f ${MEGALIB}/Makefile rev;;
  sivan)
    make -f ${MEGALIB}/Makefile siv;;
  eview)
    make -f ${MEGALIB}/Makefile evi;;
  mimrec)
    make -f ${MEGALIB}/Makefile mim;;
  megalyze)
    make -f ${MEGALIB}/Makefile meg;;
  cosima)
    make -f ${MEGALIB}/Makefile cos;;
  *) 
    make -f ${MEGALIB}/Makefile all;;
  esac
  
  # Check if the last executed program (make) was successful:
  if [ "$?" -ne 0 ]; then
    echo "Error: Compilation failed. Aborting."
    exit 1;
  fi

  command -v ${program} >/dev/null 2>&1
  programnotfound=$?
  if [ ${programnotfound} -eq 1 ]; then
    echo " "
    echo "ERROR: Program ${program} still not found! Aborting!"
    exit 1;
  fi
fi


     
# C. Lauch the program
cd ${currdir}
if [ "${DEBUGGER}" == "gdb" ]; then
  echo "Starting gdb...";
  TMP=`mktemp /tmp/megalibdebugger.XXXXXXXX`
  #echo "catch throw" >> ${TMP}
  echo "handle SIGPIPE nostop" >> ${TMP}
  echo "run ${args}" >> ${TMP}
  gdb -x ${TMP} ${program}
  rm ${TMP}
elif [ "${DEBUGGER}" == "lldb" ]; then
  echo "Starting lldb...";
  lldb -o "break set -n __cxa_throw" -o "process launch" -f ${program} -- ${args}
fi

exit 0;
