#!/bin/bash

# This is a wrapper script around the main ForceBalance.py script.
# Run: "ForceBalance [--continue] [-b] [-f] job.in [job.out]"
#
# If the output filename is not specified, it will be automatically created.
#
# If the output file already exists, then the output file will be backed up -
# unless -f is given, and then files will be overwritten.
# 
# Importantly, ForceBalance.py prints a lot of carriage returns as "progress reports".
# These carriage returns are not saved to the output file if this command is used.

minargs=1
maxargs=2
E_EXISTS=64
force=0
blkwht=0

show_help() 
{
    echo "Usage: `basename $0` [options] ForceBalance job.in [job.out]"
    echo "Values in brackets are optional."
    echo "Options are:"
    echo "  -c, --continue   Pick up an existing calculation from where we left off mid-iteration."
    echo "  -b               Black and white output file (no ANSI colors in output file)."
    echo "  -f               Force overwrite of output file."
    echo "  -h               Show this help message."
    exit 1
}

while [ $# -gt 0 ]
do
    case $1 in
        -b) blkwht=1 ;;
        -c | --continue) continue=1 ;;
        -f) force=1 ;;
        -h | --help) show_help ;;
        -* | --*) show_help;;
        *) break ;;
    esac
    shift
done

if [ $# -lt $minargs ] || [ $# -gt $maxargs ]
then
    show_help
fi

program=ForceBalance.py
input=$(basename "$1")
if [ ! -f $input ] ; then
    echo "Input file does not exist! Exiting.."
    exit 1
fi

if [ $# -eq $minargs ] ; then
    filename=$(basename "$1")
    extension="${filename##*.}"
    filename="${filename%.*}"
    output=$filename".out" 
    outext="out"
    error=$filename".err" 
    bakdir=$filename".bak" 
else
    output=$(basename "$2")
    filename="${output%.*}"
    outext="${output##*.}"
    error=$filename".err"
    bakdir=$filename".bak" 
fi

if [[ $continue == 1 ]] ; then
  echo "Continuing a previous run.."
  program="$program --continue"
  if [ -e $output ] ; then
      bnum=2
      while [[ -e ${filename}_$bnum.$outext || -e ${filename}_$bnum.err ]] ; do
          bnum=$(( bnum + 1 ))
      done
      output=${filename}_$bnum.$outext
      error=${filename}_$bnum.err
  fi
elif [ -e $output ] && [ $force -eq 0 ] ; then
  echo "Backing up the output file to $bakdir .."
  echo "Use -f option to force overwrite"
  mkdir -p $bakdir
  bnum=1
  while [[ -e $bakdir/${filename}_$bnum.$outext || -e $bakdir/${filename}_$bnum.err ]] ; do
      bnum=$(( bnum + 1 ))
  done
  cp $output $bakdir/${filename}_$bnum.$outext
  if [ -e $error ] ; then
      cp $error $bakdir/${filename}_$bnum.err
  fi
fi

echo "Output will be written to $output"

if [ $blkwht -eq 1 ] ; then
    echo "#=====================================#"
    echo -e "#|    Black and White Mode \xE0\xB2\xA0_\xE0\xB2\xA0       |#"
    echo "#|       Try color on a black        |#"
    echo "#|       terminal background!        |#"
    echo "#=====================================#"
else
    echo "#=====================================#"
    echo "#|     For black and white mode,     |#"
    echo "#|      Run this script with -b      |#"
    echo "#=====================================#"
fi

export PYTHONUNBUFFERED="y"
# Standard error gets written to its own .err file
# Text overwritten by carriage returns are not saved
if [ $blkwht -eq 1 ] ; then
    # Option for black and white output
    $program $input 2>$error | sed -u -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)*[m|K]//g" | tee >(awk -F '\r' '{print $NF}' > $output)
else
    $program $input 2>$error | tee >(awk -F '\r' '{print $NF}' > $output)
fi
exitstat=$?
if [ -f $error ] ; then
    nerr=`wc -l $error | awk '{print $1}'`
    errlines=`grep -i "error\|exception\|fatal" $error 2> /dev/null | wc -l | awk '{print $1}'`
else
    nerr=0
    errlines=0
fi
if [ $errlines -ne 0 ] || [ $exitstat -ne 0 ] ; then
    tail -50 $error
    echo
    echo "$program may not have finished successfully, see error above or look in $error."
    if [ `find $filename.tmp -name npt.out -mmin -600 | wc -l` -gt 0 ] ; then
        find $filename.tmp -name npt.out -mmin -600 | sort
        echo "Error messages may also appear in the above files."
    fi
    echo "If error does not make sense, please contact me (Lee-Ping)."
elif [ $nerr -ne 0 ] ; then
    echo "Look in $error for more (possibly relevant) printout."
else
    rm $error
fi
