#!/bin/sh
#========================================================
# This script will build a next stage GCC for EMX target
# If run first time, it will produce a stage1 compiler,
# second time - a stage2 compiler and so on.
#========================================================

# NOTE: The optimal configuration for gcc under OS2/EMX is:
# ./configure --enable-clh --enable-threads --disable-shared --prefix=/emx
# Also append --without-included-gettext if you have the gettext headers
# and library (used with some XFree86 apps, for example). You also should
# export the GMSGFMT variable

CWD=`pwd`
log='emx-build.log'
emxload -q
#export GCCLOAD=

[ -z "$SHELL" ] && SHELL=$BASH
[ -z "$SHELL" ] && SHELL=sh

for stage in 4 3 2 1 0; do
  if [ ${stage} -eq 0 ]; then
    stagedir='./'
    CC=gcc
    stageCC=gcc
  else
    stagedir=${CWD}/stage${stage}'/'
    CC=${stagedir}xgcc.exe
    stageCC="${stagedir}xgcc.exe -L${stagedir} -B${stagedir}"
  fi
  if [ ${stage} -lt 2 ]; then
    CFLAGS="-g"
    if [ ${stage} -lt 1 ]; then
      LDFLAGS="-Zexe"
    else
      LDFLAGS="-Zexe -B/emx/lib"
    fi
  else
    ### gcc 3.0 cannot complete stage 2 with -fomit-frame-pointer! :-( ###
    CFLAGS="-s -O2 -mcpu=pentium -mpreferred-stack-boundary=2 -falign-loops=2 -falign-jumps=2 -falign-functions=2 -malign-strings=0"
    LDFLAGS="-Zexe -Zcrtdll -B/emx/lib"
  fi
  if [ ${stage} -eq 0 ]; then
    LANGUAGES="c"
  else
    LANGUAGES='c gcov.exe $(CONFIG_LANGUAGES)'
  fi
  if [ ${stage} = 0 ] || [ -f ${CC} ]; then
    if [ $stage = 4 ]; then
      echo "All done"
      exit 0;
    fi
    echo "----------------------------------------------------------------------"
    echo "     Doing stage `expr ${stage} + 1` build using stage ${stage} compiler"
    echo "Building the following targets: ${LANGUAGES}"
    echo "----------------------------------------------------------------------"

    make SHELL=$SHELL CC="${stageCC}" CFLAGS="${CFLAGS}" LDFLAGS="${LDFLAGS}" \
	 OLDCC="gcc -O6 -mno-stack-align-double -s" OLDCFLAGS= \
         LOOSE_WARN="-W -Wall -Wwrite-strings -Wstrict-prototypes" \
	 exec_prefix=/emx LANGUAGES="${LANGUAGES}" $* 2>&1 | tee $log

    if [ $? = 0 ] && [ -f mt/gcc*.dll ]; then
      emxload -q
      stage=`expr ${stage} + 1`
      make stage${stage}
    fi
    break;
  fi
done

exit
