#!/bin/sh
# Copyright (C) 2014 - 2018 FARGOS Development, LLC
# Return version and/or name of C or C++ compiler
# $Id$
originDir=`dirname $0`

showVersion=1
showCompiler=0
showLibDir=0

osName=`uname -s`
case "${osName}" in
Darwin | OpenBSD) # MacOS or OpenBSD
	default_CC_Compiler="${CC:-clang}"
	default_CXX_Compiler="${CXX:-clang++}"
	;;
*)
	default_CC_Compiler="${CC:-gcc}"
	default_CXX_Compiler="${CXX:-g++}"
	;;
esac

compiler="CXX"	# assume default
defaultCompiler="${default_CXX_Compiler}"

# environment variable substitute provides ability to rename path
# to restore lost symbolic link
# BACKING_TREE_ROOT_MAP='s:/mnt/data1/export:/mnt/backingTrees:'

backingTreeSubstitutions="${BACKING_TREE_ROOT_MAP}"

while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		printf "usage: %s [{--showlib | --showld | --showprog}] [{-c | -c++}] [-noversion]\n" "$0" >&2
		exit 1
		;;
	-c)
		compiler="CC"
		defaultCompiler="${default_CC_Compiler}"
		;;
	-c++ | --c++)
		compiler="CXX"
		defaultCompiler="${default_CXX_Compiler}"
		;;
	-showlib | --showlib)
		showLibDir=1
		;;
	-showld | --showld)
		# program type is second word of version output
		# ld.gold will be gold
		# ld.bfd will be ld
		# On MacOS, a block of text is emitted. Take "PROGRAM:ld"
		echo `ld -v 2>&1 | awk '/PROGRAM/ { n = split($1, args, ":"); print args[2]; exit;} { print $2; exit; }'`

		exit 0
		;;
	-noversion | --noversion)
		showVersion=0
		;;
	-showprog | --showprog)
		showCompiler=1
		;;
	esac
	shift
done
compilerEnv="${compiler}"
compilerBinary=`eval echo "$"${compilerEnv}`
if test -z "${compilerBinary}"
then
	compilerBinary="${defaultCompiler}"
fi
execName=`basename ${compilerBinary}`
result=""
if test ${showCompiler} -eq 1
then
	result="${execName}"
fi
if test ${showVersion} -eq 0
then
	echo ${result}
	exit 0
fi
if test ${showLibDir} -eq 1
then
	# Workaround Apple LLVM clang bug that reports "darwin18.0.0" rather
	# than the actual "darwin" directory
	libName=`${compilerBinary} --print-libgcc-file-name | sed -e 's/darwin18.*.*/darwin/'`
	libDir=`dirname ${libName}`
	if test "${libDir}" = "."
	then
		exit 0
	fi
	absPath=`(cd ${libDir}; pwd)` # don't lose symbolic name
	if test -z "${backingTreeSubstitutions}"
	then
		echo ${absPath}
	else
		echo ${absPath} | sed -e ${backingTreeSubstitutions}
	fi
	exit 0
fi
case "${execName}" in
gcc* | g++* | clang* | *g++)
	version=`${compilerBinary} --version 2>/dev/null | awk '/Linaro/ { print substr($4, 1, length($4)-1) "-Linaro"; exit; } /Apple LLVM/ { print $4; exit; } /OpenBSD clang/ { print $4; exit; } { p = "[)]"; gsub(p, "", $0); print $3; exit; }'`
	;;
emcc* | em++*) # emscripten front-end
	version=`${compilerBinary} --version | awk '/^emcc / { print $5; exit; }'`
	;;
*)
	printf "%s: unknown compiler %s\n" "$0" "${execName}" >&2
	exit 1
	;;
esac
echo ${result}${result:+ }${version}
exit 0
