#!/bin/bash
# Runs a C++ compiler with various important options
# Primarily for intro students who don't know how to use makefiles yet
# v2.1.1 2014-01-29  (dpb)  Works with -c and only .u; prints uncic cmd
# v2.1   2014-01-23  (dpb)  Prints error if .h files in line
# v2.0.1 2014-01-23  (dpb)  Fixed terrible bug that _required_ .u file
# v2.0   2014-01-22  (dpb)  Introduced handling for .u files
# v1.0   2014-01-14  (dpb)

#echo Start "$@"

# Count .u files, determine whether -c is present, check for .h files
((ufiles=0))
for arg
do if [ "$arg" == "-c" ]
  then
    dashc="-c"
  elif [[ "$arg" =~ \.u$ ]]
  then
    ((++ufiles))
    ufile=$arg
  elif [[ "$arg" =~ \.h$ ]]
  then
    echo "$0: use #include for header files, don't pass .h files to compile directly (found ${arg})"
    exit 1
  fi
done

#echo Num args $#
if [[ $# -eq 0 || ${dashc} && $# -eq 1 ]]
then
  echo "$0: requires at least one filename to compile."
  exit 1
fi

# Error if multiple .u files
if [ $ufiles -gt 1 ]
then
  echo "$0: only one .u file permitted per compilation, found ${ufiles}"
  exit 1
fi

# Compile .u file to .o file
if [[ ${ufile} ]]
then
  echo uncic ${ufile}
  uncic ${ufile} || exit 1
  ofile=${ufile/%\.u/.o}
fi

# Rewrite arg list: replace .u with .o for full compile-and-link, 
# remove .u entirely if compiling -c
args=()
#echo Num args ${#args[@]}
for arg
do
  #echo Arg ${arg}
  if [[ ${dashc} && "$arg" == "${ufile}" ]]
  then : #omit from files to be compiled
  elif [[ ! ${dashc} && "$arg" == "${ufile}" ]]
  then args=("${args[@]}" "${ofile}")
  else args=("${args[@]}" "$arg")
  fi
done
if [[ ! ${dashc} && ${ufile} ]]
then args=("${args[@]}" "-lcppunit")
fi

# Resulting arg list
#echo Finish "${args[@]}"

#echo clang++ --std=c++11 -g -Wall -Wfatal-errors -ftemplate-backtrace-limit=1 -ferror-limit=1 "${args[@]}"
#clang++ --std=c++11 -g -Wall -Wfatal-errors -ftemplate-backtrace-limit=1 -ferror-limit=1 "${args[@]}"  && echo 'Success!'

#If -c and there's nothing else (already handled a .u), we're done
#Note that "-c" itself is one of the args, hence # is 1 here
#echo Num args ${#args[@]}
#echo Args "${args[@]}"
if [[ ${dashc} && ${#args[@]} -eq 1 ]]
then
  echo 'Success!'
  exit 0
fi

echo g++ --std=c++11 -g -Wall -Wfatal-errors "${args[@]}"
g++ --std=c++11 -g -Wall -Wfatal-errors "${args[@]}"  && echo 'Success!'


# Remove temp file
if [[ ! ${dashc} && ${ufile} ]]
then
  rm "${ofile}"	#temporary file, no longer needed
fi
