#!/bin/bash

# This script doesn't do anything other than print commands and print
# rewritten arguments; it shows what needs to be done in a compile
# script to make unci use transparent to students

echo Start "$@"

# Count .u files, determine whether -c is present
((ufiles=0))
for arg
do if [ "$arg" == "-c" ]
  then
    dashc="-c"
  elif [[ "$arg" =~ \.u$ ]]
  then
    ((++ufiles))
    ufile=$arg
  fi
done

# 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
echo uncic ${ufile}
ofile=${ufile/%\.u/.o}

# Rewrite arg list: replace .u with .o for full compile-and-link, 
# remove .u entirely if compiling -c
args=()
for arg
do
  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} ]]
then args=("${args[@]}" "-lcppunit")
fi

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

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