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

# If libgcc.a exists, and cc1.exe doesn't - kill it, most likely
# it is a remain of previous stage. If we won't, this can cause
# big problems with libgcc DLL
if [ -f libgcc.a ] & [ ! -f cc1.exe ]; then
  rm -f *gcc*.a
fi

for stage in 4 3 2 1 0; do
  if [ ${stage} = 0 ]; then
    stagedir='./'
    CC=gcc
    stageCC=gcc
    CFLAGS="-g"
    LFLAGS="LDFLAGS=-Zexe"
  else
    stagedir=${CWD}/stage${stage}'/'
    CC=${stagedir}xgcc.exe
    stageCC="${stagedir}xgcc.exe -L${stagedir} -B${stagedir}"
    CFLAGS="-s -O6"
    LFLAGS=""
  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 "----------------------------------------------------"
    cmd.exe /c "set BEGINLIBPATH=`echo ${stagedir}|tr "/" "\\\\\\\\"` & \
    make 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
