#!/bin/bash

# This script will build llvm and llvm-gcc and install them in the directory
# from which it is run (that is, PREFIX=`pwd`)
#
# If you already have a working LLVM (2.4) install, you do not need to run
# this and can skip right to running ./waf configure

source llvm-versions.sh

# Fetch tarballs if we need them.
if ! [[ -f tarballs/llvm-${LLVM_VERSION}.tar.gz ]]
then
  echo "Fetching llvm-${LLVM_VERSION} tarball"
  [ -d tarballs ] || mkdir tarballs
  pushd tarballs
  wget http://llvm.org/releases/${LLVM_VERSION}/llvm-${LLVM_VERSION}.tar.gz
  popd
fi

if ! [[ -f tarballs/llvm-gcc-${GCC_VERSION}-${LLVM_VERSION}.source.tar.gz ]]
then
  echo "Fetching llvm-gcc-${GCC_VERSION}-${LLVM_VERSION} tarball"
  [ -d tarballs ] || mkdir tarballs
  pushd tarballs
  wget http://llvm.org/releases/${LLVM_VERSION}/llvm-gcc-${GCC_VERSION}-${LLVM_VERSION}.source.tar.gz
  popd
fi

PREFIX=`pwd`

echo "Extracting LLVM-${LLVM_VERSION} tarball"
[ -d .build ] || mkdir .build

pushd .build

if ! [[ -x $PREFIX/bin/opt ]]
then
    tar xzf $PREFIX/tarballs/llvm-${LLVM_VERSION}.tar.gz
    echo "Building llvm"
else
    echo "llvm is already built"
fi

pushd llvm-${LLVM_VERSION}

SRC_ROOT=`pwd`
mkdir build
pushd build
OBJ_ROOT=`pwd`

OLDCFLAGS=$CFLAGS
OLDCXXFLAGS=$CXXFLAGS
# GCC 4.4 rearranged internal includes in its headers, so a few
# headers which were previously implicitly included are no longer
# visible.  This hack forcibly includes them for affected versions
# of gcc.
if [[ $(gcc -dumpversion) > "4.3.9" ]]
then
    export CFLAGS="-include stdio.h -include stdint.h $OLDCFLAGS"
    export CXXFLAGS="-include stdio.h -include stdint.h $OLDCXXFLAGS"
fi

if ! [[ -x $PREFIX/bin/opt ]]
then
    ${SRC_ROOT}/configure --prefix=$PREFIX --enable-optimized
    make -S

    if [[ $? -ne 0 ]]
    then
        echo "LLVM build failure"
        exit 1
    fi
    make install
fi
popd # Up to SRC_ROOT
popd # Up to .build
popd # Up to $PREFIX


# Build llvm-gcc if it is not already built
if ! [[ -x $PREFIX/bin/llvm-gcc ]]
then
  pushd .build
  tar xzf $PREFIX/tarballs/llvm-gcc-${GCC_VERSION}-${LLVM_VERSION}.source.tar.gz


  echo "Building llvm-gcc frontend"
  pushd llvm-gcc${GCC_VERSION}-${LLVM_VERSION}.source
  mkdir build
  pushd build

  export CFLAGS=$OLDCFLAGS
  export CXXFLAGS=$OLDCXXFLAGS
  ../configure --prefix=$PREFIX --program-prefix=llvm- --enable-llvm=${OBJ_ROOT} --enable-languages=c,c++
  make

  if [[ $? -ne 0 ]]
  then
      echo "LLVM-gcc build failure"
      exit 1
  fi

  make install

  popd # Up to llvm-gcc root
  popd # Up to .build
  popd # Up to $PREFIX
else
  echo "llvm-gcc frontend is already built"
fi