#!/bin/bash
#########################################################################################
#  Script name: valgrind_leaks
#  Created: 10/17/2012 by Eddie Hansen
#  Purpose: Compiles astrobear, runs valgrind, and checks output for memory leaks
#  Usage: ./valgrind_leaks [OPTIONS] -m module
#         specified module must be in the modules directory
#  Options: -d code_dir 
#              specify code directory (default is present working directory)
#           -sc  --skipclean
#              skip clean, but still recompiles (use only if you have previously
#              compiled with proper FFLAGS for valgrind, and you have not made changes
#              to Makefile.inc or makefile)
#           -sm  --skipmake
#              skip compiling completely if you just want to rerun
#           -sr  --skiprun
#              skip running if you already ran valgrind and just want to check output
#           -np
#              choose number of processors to run on (default is 1)
#########################################################################################

# initialization
machinename=$(hostname)
CODE_DIR=$(pwd)
MODULE=""
skipclean=false
skipcompile=false
skiprun=false
nprocs=1
maxprocs=$(cat /proc/cpuinfo | grep processor | wc -l)
USAGE_ERR="*** Usage:  $0 [OPTIONS] -m module ***"

# read in options and variables
while [ $# -gt 0 ]
do
   case "$1" in
      -d)  CODE_DIR="$2"; shift;;
      -m)  MODULE="$2"; shift;;
      -np) nprocs="$2"; shift;;
      -sc)  skipclean=true;;
      --skipclean)  skipclean=true;;
      -sm)  skipclean=true; skipcompile=true;;
      --skipmake)  skipclean=true; skipcompile=true;;
      -sr)  skipclean=true; skipcompile=true; skiprun=true;;
      --skiprun)  skipclean=true; skiptcompile=true; skiprun=true;;
      -*)  echo "*** ERROR: $1 option not recognized ***"
           echo "$USAGE_ERR"
           echo "*** See valgrind_leaks script for available options ***"
           exit 1;;
       *) break;;
   esac
   shift
done

# make sure code directory exists and that it contains astrobear code
if [ ! -d $CODE_DIR ]; then
   echo "*** ERROR: " $CODE_DIR " directory does not exist ***"
   exit 1
fi
if [ ! -f $CODE_DIR/scrambler.f90 ]; then
   echo "*** ERROR: $CODE_DIR directory does not contain astrobear code ***"
   exit 1
fi

# make sure input module exists
if [ ! -d $CODE_DIR/modules/$MODULE ]; then
   echo "*** ERROR: $MODULE module does not exist in modules directory ***"
   exit 1
fi
if [ -z $MODULE ]; then
   echo "*** ERROR: no module specified ***"
   echo "$USAGE_ERR"
   exit 1
fi

# check if this is being run on one of our local machines, and make sure nprocs is acceptable
if [[ "$machinename" == "grass" || "$machinename" == "alfalfa" || "$machinename" == "clover" || "$machinename" == "bamboo" ]]; then
   local=true
else
   local=false
fi
if (( "$nprocs" > "$maxprocs" )); then
   echo "*** ERROR: too many processors requested, $machinename only has $maxprocs processors ***"
   exit 1
fi
if (( "$nprocs" < 1 )); then
   echo "*** ERROR: number of processors requested is less than 1 ***"
   exit 1
fi

# check if valgrind paths are present, if it is a local run add valgrind paths if necessary
if [[ "$LD_LIBRARY_PATH" != *"/valgrind/lib"* ]]; then
   echo "*** ERROR: valgrind lib is not in LD_LIBRARY_PATH ***"
   if $local ; then
      echo "*** adding /home/johannjc/local/valgrind/lib to LD_LIBRARY_PATH ***"
      export LD_LIBRARY_PATH=/home/bshroyer/local/valgrind/lib:$LD_LIBRARY_PATH
   else
      exit 1
   fi
fi
if [[ "$PATH" != *"/valgrind/bin"* ]]; then
   echo "*** ERROR: valgrind bin is not in PATH ***"
   if $local ; then
      echo "*** adding /home/johannjc/local/valgrind/bin to PATH ***"
      export PATH=/home/johannjc/local/valgrind/bin:$PATH
   else
      exit 1
   fi   
fi

# set up symbolic links and clean if necessary, then compile if necessary
cd $CODE_DIR
if ! $skipclean ; then 
   if [ -e $CODE_DIR/Makefile.inc ]; then rm $CODE_DIR/Makefile.inc; fi
   if [ -e $CODE_DIR/modules/Problem ]; then rm $CODE_DIR/modules/Problem; fi
   ln -s $CODE_DIR/Makefile.inc.$machinename $CODE_DIR/Makefile.inc
   ln -s $CODE_DIR/modules/$MODULE $CODE_DIR/modules/Problem
   make clean

   # ensures optimization flags are off, and check flags are on
   # by default sed will break the symbolic link, so the original
   # Makefile.inc.machinename will remain unchanged
   sed -i "" -e 's/FFLAGS=-O/#FFLAGS=-O/g' $CODE_DIR/Makefile.inc
   sed -i "" -e 's/#FFLAGS=-g -traceback/FFLAGS=-g -traceback/g' $CODE_DIR/Makefile.inc
   sed -i "" -e 's/##FFLAGS=/#FFLAGS=/g' $CODE_DIR/Makefile.inc
fi
if ! $skipcompile ; then 
   if [ ! -e Makefile.inc ]; then 
      echo "*** ERROR: Makefile.inc does not exist, clean make may be necessary ***"
      exit 1
   fi
   currentflags=$(grep "FFLAGS=" Makefile.inc | grep -v "#FFLAGS")
   if [[ "$currentflags" != *"-g"* || "$currentflags" == *"-O"* ]]; then
      echo "*** ERROR: improper FFLAGS for compiling to run valgrind, clean make may be necessary ***"
      exit 1
   fi
   make
fi
if ! $skiprun ; then
   if [ ! -e $CODE_DIR/astrobear ]; then
      echo "*** ERROR: astrobear was not compiled successfully ***"
      exit 1
   fi
fi

# make out directory, remove old valgrind output if necessary
STD_VALGRIND_OUT=$CODE_DIR/modules/$MODULE/valgrind_dump.txt
cd $CODE_DIR/modules/$MODULE
if ! $skiprun ; then
   if [ -d $CODE_DIR/modules/$MODULE/out ]; then rm -r $CODE_DIR/modules/Problem/out; fi
   mkdir $CODE_DIR/modules/$MODULE/out
   if [ -e $STD_VALGRIND_OUT ]; then rm $STD_VALGRIND_OUT; fi

   mpiexec -np $nprocs valgrind -v --leak-check=full --leak-resolution=high --num-callers=40 --read-var-info=yes --track-origins=yes --log-file="$STD_VALGRIND_OUT" $CODE_DIR/astrobear
fi

if [ ! -e $STD_VALGRIND_OUT ]; then
   if $skiprun ; then
      echo "*** ERROR: valgrind output does not exist in $MODULE directory ***"
   else
      echo "*** ERROR: astrobear/valgrind run error, valgrind output not created ***"
   fi
   exit 1
fi

# print only leak tracebacks related to astrobear to astrobear_leaks.out
awk '/lost/{if(l)print s;l=0;s=$0;next}/for_allocate/{l=1}{s=s RS $0}END{if(l)print s}' $STD_VALGRIND_OUT > astrobear_leaks.out

# print error message if astrobear_leaks.out contains leaks
if [ -s astrobear_leaks.out ]; then
   echo "*** found memory leaks in astrobear ***"
   echo "*** check astrobear_leaks.out for the tracebacks ***"
else
   echo "*** no memory leaks in astrobear detected :) ***"
fi
