#!/bin/sh

PROGRAM_NAME="cc-compile"

warning()
{
  echo "${PROGRAM_NAME}: warn: $1" 1>&2
}

error()
{
  echo "${PROGRAM_NAME}: error: $1" 1>&2
}

fatal()
{
  echo "${PROGRAM_NAME}: fatal: $1" 1>&2
  exit 1
}

if [ $# -lt 1 ]
then
  echo "${PROGRAM_NAME}: usage: [@dir] source" 1>&2
  exit 1
fi

#
# check if new base dir was specified
#

BASE_DIR="."
if [ $# -gt 1 ]
then
  echo "$1" | grep '^@' >/dev/null
  if [ $? -eq 0 ]
  then
    BASE_DIR=`echo "$1" | sed 's/^@//g'`
    shift
  fi
fi

#
# Extract base name of given source file.
#

out=`echo "$1" | awk -F. '{print $1}'`
src="$1"
shift

#
# Assume source is being cross compiled if there is a cross-compiler
# defined.
#

if [ -f "${BASE_DIR}/conf-x-cc" ]
then
  ok=1

  CC=`head -n 1 "${BASE_DIR}/conf-x-cc"`
  if [ $? -ne 0 ]
  then
    error "could not read ${BASE_DIR}/conf-x-cc"
    ok=0
  fi
  SYS_TYPE=`head -n 1 "${BASE_DIR}/conf-x-systype"`
  if [ $? -ne 0 ]
  then
    error "could not read ${BASE_DIR}/conf-x-systype"
    ok=0
  fi
  CC_TYPE=`head -n 1 "${BASE_DIR}/conf-x-cctype"`
  if [ $? -ne 0 ]
  then
    error "could not read ${BASE_DIR}/conf-x-cctype"
    ok=0
  fi
  CC_FLAGS="${CC_FLAGS} `head -n 1 "${BASE_DIR}/conf-x-cflags" 2>/dev/null`"

  if [ $ok -eq 0 ]
  then
    fatal "could not read required configuration files for cross compilation"
  fi
else
  CC=`head -n 1 "${BASE_DIR}/conf-cc"`
  if [ $? -ne 0 ]
  then
    fatal "could not read ${BASE_DIR}/conf-cc"
  fi
  SYS_TYPE=`head -n 1 "${BASE_DIR}/conf-systype"`
  if [ $? -ne 0 ]
  then
    fatal "could not read ${BASE_DIR}/conf-systype"
  fi
  CC_TYPE=`head -n 1 "${BASE_DIR}/conf-cctype"`
  if [ $? -ne 0 ]
  then
    fatal "could not read ${BASE_DIR}/conf-cctype"
  fi
fi

CC_FLAGS="${CC_FLAGS} `head -n 1 ${BASE_DIR}/conf-cflags 2>/dev/null`"

#
# Read global flag file list, if present.
#

if [ -f "${BASE_DIR}/conf-ccfflist" ]
then
  for f in `cat "${BASE_DIR}/conf-ccfflist"`
  do
    FLAGS=`cat $f 2>/dev/null`
    CC_FLAGS="${CC_FLAGS} ${FLAGS}"
  done
fi

#
# Read local flag file list, if present.
#

if [ -f "${out}.iff" ]
then
  for f in `cat "${out}.iff"`
  do
    targ="`dirname $out`/`dirname $f`/`basename $f`"
    FLAGS="`cat $targ 2>/dev/null`"
    CC_FLAGS="${CC_FLAGS} ${FLAGS}"
  done
fi

#
# compensate for any compiler bugs
#

case ${SYS_TYPE} in
  DARWIN)
    case ${CC_TYPE} in
      GCC)
        CC_FLAGS="${CC_FLAGS} -fno-common"  # darwin linker bug workaround
        ;;
      *)
        ;;
    esac
    ;;
  *)
    ;;
esac

exec ${CC} -o ${out}.o -c ${src} ${1+"$@"} ${CC_FLAGS}
