#!/bin/sh -x

# Usage:
# build-lldb-llvm-clang <revision> [Debug|Release|BuildAndIntegration]
# build-lldb-llvm-clang <llvm-revision> <clang-revision> [Debug|Release|BuildAndIntegration]

LLVM_REVISION=$1
CLANG_REVISION=$2
LLVM_CONFIGURATION=$3

if [ "$LLVM_REVISION" = "" ]; then
	echo "Usage:\n    build-lldb-llvm-clang <llvm-revision> [<clang-revision> Debug|Release||BuildAndIntegration]"
	exit 1
fi

if [ "$CLANG_REVISION" = "" ]; then
	$CLANG_REVISION = $LLVM_REVISION
fi

# Checkout LLVM
svn co -q -r $LLVM_REVISION http://llvm.org/svn/llvm-project/llvm/trunk llvm

# change directory to "./llvm"
cd llvm

# Checkout Clang
# change directory to "./llvm/tools"
cd tools
svn co -q -r $CLANG_REVISION http://llvm.org/svn/llvm-project/cfe/trunk clang

# change directory to "./llvm"
cd ..
for patch_file in ../scripts/llvm.*.diff
do
	echo "Applying patch from '$patch_file'"
    patch -p0 < "$patch_file"
done

# change directory to "./llvm/tools/clang"
cd tools/clang
for patch_file in ../../../scripts/clang.*.diff
do
	echo "Applying patch from '$patch_file'"
    patch -p0 < "$patch_file"
done

# change directory to "./"
cd ../../..
pwd

if [ "$LLVM_CONFIGURATION" = "Debug" ]; then
	# Configure "Debug+Asserts" build
	mkdir llvm-debug
	cd llvm-debug
	../llvm/configure --enable-targets=x86_64,arm 
	make -j8 clang-only VERBOSE=1 PROJECT_NAME='llvm'
	make -j8 tools-only VERBOSE=1 PROJECT_NAME='llvm' EDIS_VERSION=1
elif [ "$LLVM_CONFIGURATION" = "Release" ]; then
	# Configure "Release" build
	mkdir llvm-release
	cd llvm-release
	../llvm/configure --enable-targets=x86_64,arm --enable-optimized --disable-assertions
	make -j8 clang-only VERBOSE=1 PROJECT_NAME='llvm'
	make -j8 tools-only VERBOSE=1 PROJECT_NAME='llvm' EDIS_VERSION=1
elif [ "$LLVM_CONFIGURATION" = "BuildAndIntegration" ]; then
	# Don't configure or build for "BuildAndIntegration", this configuration 
	# is a preparation step for a build submission
	
	# Remove all patches, and the llvm and clang "test" directories
	rm -rf ./scripts/*.diff ./llvm/test ./llvm/tools/clang/test
else
	echo "checked out llvm (revision $LLVM_REVISION) and clang (revision $CLANG_REVISION)."
	exit 0
fi
