support ccache to speed up ttcn3 test compilation

By default, if ccache is found in PATH when regen-makefile.sh runs,
use cached compiled C++ object files during the build (or populate
the cache in case an object is not cached yet). Objects are cached
in ccache's default cache directory (~/.ccache) unless overriden by
the CCACHE_DIR environment variable.

The USE_CCACHE environment variable overrides auto-detection
in regen-makefile.sh and disables (USE_CCACHE=0) or enables
(USE_CCACHE=1) use of ccache.

Rebuilding the test suite from scratch with a populated cache
is an order of magnitude faster than doing an initial build.
ccache only speeds up C++ (.cc) to object file (.o) compilation.
Linking object (.o) files into shared object (.so) files is still
performed by the real compiler during every build.

Change-Id: Ibb538f602206535c06980f88191c1dabe3c4cd82
diff --git a/regen-makefile.sh b/regen-makefile.sh
index 57eebff..6b32f75 100755
--- a/regen-makefile.sh
+++ b/regen-makefile.sh
@@ -12,6 +12,16 @@
 
 test -x "$(which ttcn3_makefilegen 2>/dev/null)" || { echo "ERROR: ttcn3_makefilegen not in PATH"; exit 1; }
 
+# Enable ccache if it can be found in path.
+# This speeds up repeated builds of the TTCN3 tests by an order of magnitude
+# since most of the generated C++ source files don't change very often.
+# Roughly, for an initial build which takes N minutes, a complete rebuild
+# after 'make clean' will only take N seconds with ccache.
+# Note that ccache cannot speed up compilation of .o files to .so files.
+if [ -z "$USE_CCACHE" ] && which ccache 2>/dev/null; then
+	USE_CCACHE=1
+fi
+
 ttcn3_makefilegen -p -l -f $*
 sed -i -e 's/# TTCN3_DIR = /TTCN3_DIR = \/usr/' Makefile
 sed -i -e 's/LDFLAGS = /LDFLAGS = -L \/usr\/lib\/titan /' Makefile
@@ -32,3 +42,11 @@
         sed -i -e 's/TTCN3_DIR = $/TTCN3_DIR = \/usr/' Makefile
 fi
 sed -i -e 's/\/bin\/compiler/\/bin\/ttcn3_compiler/' Makefile
+
+if [ "x$USE_CCACHE" = "x1" ]; then
+	# enable ccache
+	sed -i -e 's/^CXX = g++ $/CXX = env CCACHE_SLOPPINESS=time_macros ccache g++/' Makefile
+	# Append the -D option to compiler flags. This option disables timestamps
+	# inside comments in the generated C++ code which interfere with ccache.
+	sed -i -e 's/^COMPILER_FLAGS = \(.*\)/&-D/' Makefile
+fi