#!/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.
#========================================================

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} = 0 ]; then
    stagedir='./'
    CC=gcc
    stageCC=gcc
    CFLAGS="-g"
    LFLAGS="LDFLAGS=-Zexe"
    LANGUAGES="c"
  else
    stagedir=${CWD}/stage${stage}'/'
    CC=${stagedir}xgcc.exe
    stageCC="${stagedir}xgcc.exe -L${stagedir} -B${stagedir}"
    CFLAGS="-s -O4 -fomit-frame-pointer"
    LFLAGS=""
    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}" ${LFLAGS} \
	 OLDCC="gcc -O6 -mno-stack-align-double -s" OLDCFLAGS= \
	 $* 2>&1 | tee $log

    if [ $? = 0 ] && [ -f gcc_p.a ]; then
      emxload -q
#      stage=`expr ${stage} + 1`
#      make stage${stage}
    fi
    break;
  fi
done

exit
