#!/bin/sh

[ $# -ge 1 ] && [ "x$1" = "x-v" ] && { verbose=1; shift; } || verbose=0

if [ -r /usr/common/libinclude/attribute-init ]
  then
      . /usr/common/libinclude/attribute-init
  else
      ATTR_red="$(/usr/bin/tput AF 1)"
      ATTR_green="$(/usr/bin/tput AF 2)"
      ATTR_yellow="$(/usr/bin/tput AF 3)"
      ATTR_normal="$(/usr/bin/tput me)"
fi

# We cd to "/" before running "clang", so that the program won't be fooled if our CWD is named something
# like " ... -target-feature +fred " - not likely, but possible, and we wanna be BULLET-PROOF!
cd / && /usr/bin/env -i /usr/bin/clang -v -x c -march=native -fsyntax-only -o /dev/null /dev/null 2>&1 | /usr/bin/awk -v verbose="$verbose" -v red="$ATTR_red" -v green="$ATTR_green" -v yellow="$ATTR_yellow" -v normal="$ATTR_normal" '
    function jljsort(unsorted)
      {
        result = ""
        count = split (substr (unsorted, 2), unsorted_arr, ",")
        for (loop1 = 1; loop1 <= count; loop1++)
          {
            match_pos = -1

            for (loop2 = 1; loop2 <= count; loop2++)
              {
                if (loop2 in unsorted_arr && (match_pos == -1 || unsorted_arr[loop2] < match_value))
                  {
                    match_value = unsorted_arr[loop2]
                    match_pos = loop2
                  }
              }

            result = result ", " match_value
            delete unsorted_arr[match_pos]
          }

        return substr (result, 3)
      }

    BEGIN \
      {
        features_plus    = ""
        features_minus   = ""
        features_unknown = ""
      }

    ($1 == "\"/usr/bin/clang\"") \
      {
        if (verbose == 1) printf "%s\n\n", $0

        loop = 1
        while (loop < NF)
          {
            if ($loop == "-target-feature")
              {
                what = substr ($(loop + 1), 1, 1)
                feature = substr ($(loop + 1), 2)

                if (what == "+") features_plus = features_plus "," feature
                  else if (what == "-") features_minus = features_minus "," feature
                    else features_unknown = features_unknown "," feature
                 loop++
              }
            loop++
          }

        triple = $0
        sub ("^.* -triple ","", triple)
        sub (" .*$", "", triple)

        target_cpu = $0
        sub ("^.* -target-cpu ","", target_cpu)
        sub (" .*$", "", target_cpu)

        printf "Clang \"native\" target for this machine: %s  (Triple: %s)\n\n", target_cpu, triple

        if (features_plus    != "") print "Features enabled  (+) : " green  jljsort(features_plus)    normal
        if (features_minus   != "") print "Features disabled (-) : " yellow jljsort(features_minus)   normal
        if (features_unknown != "") print "Features unknown  (?) : " red    jljsort(features_unknown) normal
      }

    ($1 == "error:" || $1 == "warning:" || $1 == "clang:")
  '
