#!/bin/bash
# Build a CCS v5 or V5 project in an automated fashion
#
# Args:
# build_dsp.sh projectdir projectname configs
# 
# Set the exit on error status
set -e
xvfb_pid=0
# Error hanlder to clean up, etc...
function onexit() {
    local exit_status=${1:-$?}
    echo Exiting $0 with $exit_status
    # if we started the Xvfb server then we should stop it
    if [ 0 -ne $xvfb_pid ]
    then
        kill $xvfb_pid
    fi
    exit $exit_status
}

function die()
{
	echo "$*"
	onexit 2
}

# install error handler...
trap onexit INT TERM EXIT

# Set these vars before setting the -u option so
# bash doesn't complain about unbound vars..
#projdir=/home/mikew/mityomapl138/sw/DSP/lib/SigProc
#projname=SigProc
#config=Debug
projdir=$1
shift
projname=$1
shift

# Set "fail on unset var"
set -u

workspace=/tmp/workspace_$$
cdir=/tmp/.eclipse_$$

#eclipse="/usr/local/CCSv5/ccsv5/eclipse/eclipse -noSplash -data ${workspace} -configuration @none -user @none"
eclipse="/opt/ti/ccsv5/eclipse/eclipse -noSplash -data ${workspace} -configuration @none -user @none"
importcmd="-application com.ti.ccstudio.apps.projectImport"
buildcmd="-application com.ti.ccstudio.apps.projectBuild"


[ -x /usr/bin/Xvfb ] || die "$0 need xvfb installed"
(ps aux|grep Xvfb | grep -v grep > /dev/null) || (
    /usr/bin/Xvfb :1 -screen 0 800x600x24 < /dev/null > /dev/null 2>&1 &
	xvfb_pid=$!
)

export DISPLAY=:1.0

# make a blank workspace
rm -rf ${workspace}
mkdir ${workspace}
rm -rf ${cdir}
mkdir -p ${cdir}

# import / copy the project into the workspace
${eclipse} ${importcmd} -ccs.location ${projdir} -ccs.autoImport

# build all configurations specified
while (( "$#" )); do
${eclipse} ${buildcmd} -ccs.projects ${projname} -ccs.configuration $1
shift
done
