#! /bin/sh

# Copyright (c) 1994-2008 by Marc Feeley, All Rights Reserved.

herefromroot="prebuilt/macosx"
rootfromhere="../.."

if [ "`id -un`" != "root" ] ; then
  echo "You must execute this script as root!"
  echo "Try executing the command:"
  echo "  sudo $0"
  exit 1
fi

export INSTALL_PREFIX="/Library/Gambit-C"

cd "`dirname $0`"

for VARIANT in intel32 intel64 G3 G4 G5 universal; do

  cd "$rootfromhere"

  case "$VARIANT" in
      intel32) CONFIG_ARCH="-arch i686"
               CONFIG_HOST="--host=i386-apple-darwin9"
               RUN_TESTS=1
               ;;
      intel64) CONFIG_ARCH="-arch x86_64 -m64"
               CONFIG_HOST="--host=i386-apple-darwin9"
               RUN_TESTS=0
               ;;
           G3) CONFIG_ARCH="-arch ppc750"
               CONFIG_HOST="--host=powerpc-apple-darwin9"
               RUN_TESTS=0
               ;;
           G4) CONFIG_ARCH="-arch ppc7400"
               CONFIG_HOST="--host=powerpc-apple-darwin9"
               RUN_TESTS=0
               ;;
           G5) CONFIG_ARCH="-arch ppc970 -m64"
               CONFIG_HOST="--host=powerpc-apple-darwin9"
               RUN_TESTS=0
               ;;
    universal) CONFIG_ARCH="-arch i686 -arch ppc750"
               CONFIG_HOST=""
               RUN_TESTS=1
               ;;
  esac

  # In order for the executables to run with MacOS Tiger as well as
  # Leopard we need to use the MacOSX10.4u SDK.  But to do that with
  # the current Xcode you need to create this symbolic link first:
  #   % sudo ln -s /Developer/SDKs/MacOSX10.4u.sdk/usr/lib/crt1.o /Developer/SDKs/MacOSX10.4u.sdk/usr/lib/crt1.10.5.o

  SYSROOT="/Developer/SDKs/MacOSX10.4u.sdk"

  CFLAGS="-isysroot $SYSROOT $CONFIG_ARCH" LDFLAGS="-Wl,-syslibroot,$SYSROOT $CONFIG_ARCH" ./configure "$CONFIG_HOST" --prefix="$INSTALL_PREFIX" --enable-single-host # --enable-gcc-opts

  cd "$herefromroot"

  chmod +x build-phase2

  ./build-phase2 "$VARIANT" "$RUN_TESTS" > build-phase2.out

  cat build-phase2.out

  SUCCESS=0

  if fgrep "************ TESTS SUCCESSFUL" build-phase2.out > /dev/null; then
    SUCCESS=1
  else
    if fgrep "************ TESTS SKIPPED" build-phase2.out > /dev/null; then
      SUCCESS=1
    fi
  fi

  rm -f build-phase2.out

  if [ "$SUCCESS" == "1" ] ; then
    echo "************ BUILD SUCCESSFUL ($VARIANT variant)"
  else
    echo "************ BUILD FAILED ($VARIANT variant)"
    exit 1
  fi

done

echo "************ macosx BUILD SUCCESSFUL"
