#!/bin/sh
#
# Script to build firmware for FMC-based AIDA mini-TLU
#
# This script creates an ISE project.
#
# Create a working directory and execute this script....
# 
# Once project has been created either open in ISE or
# execute the build_bitstream.sh script.
#
# David Cussans, December 2013
#

export FW_WORKSPACE=`pwd`
echo "Current directory = " $FW_WORKSPACE
export BOARD_TYPE=sp605
export ISE_VER=ise14
export VERSION=trunk

echo "Setting up AIDA mini-TLU code version $VERSION"

# Check out FMC-MTLU code
TLUDir=`pwd`/fmc-mtlu
if [ ! -d "$TLUDir" ]; then
    echo "Checking out AIDA mini-TLU code"
    mkdir fmc-mtlu
    pushd fmc-mtlu
    svn co http://svn.ohwr.org/fmc-mtlu/${VERSION}/firmware
    popd
    echo "Checked out FMC-MTLU code"
fi

# Check out IPBus code
IPBusDir=`pwd`/IPBus2
if [ ! -d "$IPBusDir" ]; then
    mkdir $IPBusDir
    pushd $IPBusDir
    svn co http://svn.cern.ch/guest/cactus/tags/ipbus_fw/ipbus_2_0_v1/firmware
    echo "Checked out IPBus2 code"
    popd
fi

# Check out directory for external cores ( e.g. I2C)
if [ ! -d "external" ]; then
    echo "Checking out I2C code"
    svn co http://cactus.hepforge.org/svn/tags/firmware_pre_131_RAL/firmware/external
fi

# Create a directory contain the build products.
WorkDir=workspace
if [ ! -d "$WorkDir" ]; then
    mkdir workspace
    mkdir workspace/ipcore_dir
    echo "Made workspace"
fi

export REPOS_BUILD_DIR=`pwd`/workspace

pushd workspace

#  Create soft links to ipbus, fmc-mtlu code , i2c code
if [ ! -e "ipbus" ]; then
    ln -s $IPBusDir ipbus
fi

if [ ! -e "fmc-mtlu" ]; then
    ln -s ../fmc-mtlu .
fi

if [ ! -e "external" ]; then
    ln -s ../external .
fi


if [ ! -e "file_list" ]; then
    ln -s $TLUDir/firmware/config/$ISE_VER/$BOARD_TYPE/file_list .
fi 

if [ ! -e "ipbus" ]; then
    ln -s ../$IPBusDir/firmware/config/$ISE_VER/$BOARD_TYPE/file_list .
fi 


pushd ipcore_dir
if [ ! -e "coregen.cgp" ]; then
    ln -s $TLUDir/firmware/config/$ISE_VER/$BOARD_TYPE/coregen.cgp .
fi
popd

#export REPOS_FW_DIR=$IPBusDir
export REPOS_FW_DIR=ipbus

echo "IPBus directory = " $IPBusDir
echo "FMC-MTLU directry = " $TLUDir

xtclsh $TLUDir/firmware/config/$ISE_VER/$BOARD_TYPE/setup_project.tcl

echo "Finished setting up ISE project."
echo "Open in $ISE_VER and build bit-stream ,or execute build_bitstream.sh"
