#!/bin/sh
# $Id: clang-version.in 7100 2012-10-27 18:26:38Z cher $
# Copyright (c) 2012 Alexander Chernov <cher@ejudge.ru>

# compiler script interface is as follows
# <comp>-version [OPTION]
# OPTION is:
#  -r P fully check the availability of the compiler (like configure
#       script does). P is a proposed path to the compiler (like in
#       --with-<comp> configure option).
#       returns failure (exit code 1), if the compiler is not available
#       or is not functional.
#       in case of success exit code is 0, and the necessary configuration
#       variables are written to stdout.
#  -v   verbose operation (configure mode)
#  -l   output the compiler name to the stdout (list mode)
#  -p   write to the stdout the command line of the compiler
#  -f   write the compiler full name and the compiler version

LANG_CONFIG_DIR="/home/judges/compile/conf/lang.d"

common_config() {
  echo 'long_name="clang C"'
  echo 'src_sfx=".c"'
  echo 'arch="linux-shared"'
}

failure() {
  rm -f conftest*
  echo 'version='
  echo 'arg="'"${arg}"'"'
  common_config
  echo 'CLANGRUN=false'
  echo 'CLANGDIR='
  [ "${verbose}" = 1 ] && echo "no" >&2
  exit 1
}

unset LANG
unset LC_ALL
unset LC_MESSAGES
unset LANGUAGE

if [ x"$1" = x-v ]
then
  verbose=1
  shift
fi

# recheck the language
if [ x"$1" = x-r ]
then
  arg="$2"
  [ x"$2" != x ] && CLANGRUN="$2"
  [ "${CLANGRUN}" = "" ] && CLANGRUN="clang"

  [ "${verbose}" = 1 ] && echo -n "checking whether clang C is available... " >&2
  "${CLANGRUN}" -v >/dev/null 2>&1 || failure
  version=`"${CLANGRUN}" -v 2>&1 | grep "clang version" | gawk '{ print $3; }'`|| failure
  cat > conftest.c <<EOF
#include <stdio.h>
int main(void) { printf("ok\n"); return 0; }
EOF
  "${CLANGRUN}" conftest.c -o conftest >/dev/null 2>&1 || failure
  [ -x conftest ] || failure
  ./conftest >/dev/null 2>&1 || failure

  rm -f ./conftest*
  CLANGDIR=`dirname "${CLANGRUN}"`
  [ "${CLANGDIR}" = . ] && CLANGDIR=""
  echo 'version="'"${version}"'"'
  echo 'arg="'"${arg}"'"'
  common_config
  echo 'CLANGRUN="'"${CLANGRUN}"'"'
  echo 'CLANGDIR="'"${CLANGDIR}"'"'
  [ "${verbose}" = 1 ] && echo "yes, ${CLANGRUN}, ${version}" >&2
  exit 0
fi

if [ x"$1" = x-l ]
then
  echo "clang C compiler [http://llvm.org]"
  exit 0
fi

[ "${EJUDGE_LANG_CONFIG}" = "" ] && EJUDGE_LANG_CONFIG="${LANG_CONFIG_DIR}/clang.cfg"

if [ -f "${EJUDGE_LANG_CONFIG}" ]
then
  . "${EJUDGE_LANG_CONFIG}"
else
  CLANGRUN="clang"
  CLANGDIR=
fi

if [ x"${CLANGRUN}" = x -o x"${CLANGRUN}" = xfalse ]
then
  echo "This language is not supported." >&2
  exit 1
fi

if [ x"${CLANGDIR}" != x ]
then
    PATH="${CLANGDIR}:${PATH}"
fi

if [ x"$1" = x-p ]
then
    echo "${CLANGRUN}"
    exit 0
fi
    
"${CLANGRUN}" -v >/dev/null 2>&1 || exit 1

[ x"$1" = x-f ] && echo -n "clang C "

"${CLANGRUN}" -v 2>&1 | grep "clang version" | gawk '{ print $3; }'