#!/usr/bin/env bash

DESCRIPTION="\
Description: Update the LunarGLASS project, and rebuild the needed files.
             This is a quicker option than doing './install build'.
             If you get an error message talking about intrinsics, try running
             with the -f option.
"

DEPENDENCIES="\
Dependencies: LunarGLASS
"

USAGE="\
Usage: ./update [options]

       Options:
         -h --help        Print out this Usage info
         -f --force-llvm  Force a clean recompilation of LLVM
"

# Main functionality
function showHelp {
    echo "$DESCRIPTION"
    echo "$DEPENDENCIES"
    echo "$USAGE"
}

function all {
    echo "Updating SVN"
    rm -rf tests                # TODO: make less hackish
    svn update

    echo "Building LLVM"
    pushd LLVM/llvm-2.9/build || exit 1

    if [[ -n $FORCE ]]; then
        cd ..
        rm -rf build
        mkdir -p build
        cd build
        ../configure || exit 1
        make || exit 1
        make install DESTDIR=`pwd`/install || exit 1
    else
        make || exit 1
    fi
    popd
    echo "LLVM built"

    echo "Building LunarGLASS"
    pushd mesa/src/glsl
    make -f StandAlone.makefile clean || exit 1
    make -f StandAlone.makefile StandAlone || exit 1

    rm -rf ../../../bin/LunarGLASS || exit 1
    rm -rf ../../../tests || exit 1
    mkdir -p ../../../tests/glsl || exit 1
    mkdir -p ../../../tests/tgsi || exit 1

    install StandAlone ../../../bin/LunarGLASS || exit 1
    install ../LunarGLASS/test/*  ../../../tests || exit 1
    popd
    echo "LunarGLASS built"
    echo
    echo "Building done, binary located at bin/LunarGLASS"
    echo "Tests located in tests"
    echo "Example run: bin/LunarGLASS tests/test.frag"
}

# Command-line argument Handling

# No arguments passed
if [[ -z "$*" ]]; then all; fi;

FORCE=""
# Arguments passed
for i in $*; do
    case $i in
        -f|--force-llvm)
            FORCE="true"
            echo "Forcing a recompilation of LLVM"
            all
            ;;
        -h|--h)
            showHelp
            exit 0
            ;;
        *)
            showHelp
            exit 1
            ;;
    esac
done

echo "Done"

