#!/bin/sh

############################################################
# Copyright (c) 2009-2023 by Aleksey Cheusov
#
# See LICENSE file in the distribution.
############################################################

set -e

LC_ALL=C
export LC_ALL

: ${CHECK_COMMON_SH_DIR:=/usr/lib/mk-configure}

: ${TMPDIR:=/tmp}
: ${CC:=cc}
: ${CXX:=c++}

tmpfile="$TMPDIR/mk-c.$$.c"
trap 'rm -f "$tmpfile"' 0

##################################################

pathpart=cc_type
langname='C'

while getopts x f; do
    case "$f" in
	x)
	    pathpart=cxx_type
	    langname='C++'
	    CC="$CXX"
	    export CC;;
	*)
	    exit 2;;
    esac
done

##################################################
checks() {
    cat <<'EOF'
       __clang__   clang   __clang_major__.__clang_minor__.__clang_patchlevel__
           __ICC   icc     __ICC
__INTEL_COMPILER   icc     __INTEL_COMPILER
         __PCC__   pcc     __PCC__.__PCC_MINOR__.__PCC_MINORMINOR__
        __GNUC__   gcc     __GNUC__.__GNUC_MINOR__.__GNUC_PATCHLEVEL__
 __ARMCC_VERSION   armcc    __ARMCC_VERSION
        _MSC_VER   msc     _MSC_VER
        __HP_aCC   hpc     __HP_aCC
         __HP_cc   hpc     __HP_aCC
   __SUNPRO_C      sunpro  __SUNPRO_C
  __SUNPRO_CC      sunpro  __SUNPRO_CC
     __IBMCPP__    ibmc    __xlC__
       __IBMC__    ibmc    __xlC__
    __BORLANDC__   bcc     __BORLANDC__
  __WATCOMC__      watcom  __WATCOMC__
       __COMO__    como    __COMO_VERSION__
         __DECC    decc    __DECC_VER
       __DECCXX    decc    __DECCXX_VER
_COMPILER_VERSION  mipspro __COMPILER_VERSION
EOF
}

check_itself (){
    checks |
    /usr/bin/gawk '
BEGIN {
   printf "#"
}
{
   printf "if defined(%s)\ncompiler %s %s\n#el", $1, $2, $3
}
END {
   printf "se\ncompiler unknown 0\n#endif\n"
}' >"$tmpfile"

    $CC -E "$tmpfile" |
    /usr/bin/gawk 'BEGIN { ret="unknown"}
	$1 == "compiler" {
	    sub(/\r$/, "")
	    compiler = $2
	    $1 = $2 = ""
	    gsub(/ /, "", $0)
	    ret=(compiler " " $0)
	    exit
	}
	END { printf("%s ", ret) }'
    triplet=`$CC -dumpmachine 2>/dev/null || true` # double "$CC -dumpmachine" die to POSIX shell /-)
    if $CC -dumpmachine > /dev/null 2>&1; then
	:
    else
	triplet="$(uname -m)-unknown-$(uname -s)" # "uname -m" because "uname -p" is not POSIX
    fi
    printf '%s\n' "$triplet"
}

. ${CHECK_COMMON_SH_DIR}/mkc_check_common.sh

check_and_cache "checking $langname compiler type" "$cache"

printme '%s\n' "$ret" 1>&2

echo "$ret"
