#!/bin/bash
#
# Low brow build script for Mono 2.0.
# Uses metadata available in VS2005 project files.
#
# Replace with Mono's new XBuild when details are fully released.
# Note: XBuild is a clone of MSBuild.
#

#MCS_FLAGS="-debug+"
MCS_FLAGS="-optimize"
outDir=$PWD/build/mono

FindExternalReferences() 
{
  assembly=$1
  grep HintPath $assembly.csproj | sed -e 's-.*<HintPath>\(.*\)</HintPath>-\1-' -e 's-\\-/-g' |
  while read ref; do
    echo $PWD/$ref
  done
}

Build()
{
  assembly=$1; shift

  echo "===================================================="
  echo Building $assembly
  references=$(grep '<ProjectReference' $assembly/$assembly.csproj | sed -e 's-.*"\(.*\)".*-\1-' -e 's-\\-/-g' | 
    while read file; do
      echo $(basename $file .csproj); 
    done)
  references=$(echo $references)
  echo "Projects referenced = [$references]"
  (
    regularRefs=""
    for ref in $references; do
      regularRefs="$regularRefs $outDir/$ref.dll"
    done
    cd $assembly
    find . -name \*.cs >tmp.build.sources
    externalReferences=$(FindExternalReferences $assembly)
    # Strip Control-M characters from external references...
    externalReferences=$(echo $externalReferences | sed 's/\r//g')
    echo "externalReferences = [$externalReferences]"
    echo "regularRefs = [$regularRefs]"
    echo PWD=$PWD

    # construct "-r" argument.
    fullrefs=""
    for ref in $regularRefs $externalReferences; do
      if [[ -z $fullrefs ]]; then
        fullrefs="-r:$ref"
      else
        fullrefs="$fullrefs,$ref"
      fi
    done
    echo "fullrefs = [$fullrefs]"

    # Copy external references to output directory.
    for ref in $externalReferences; do
      cp $ref $outDir
    done

    # Strip Control-M character here too. Not sure how they get there...
    echo $fullrefs >tmp.references
    mcs $MCS_FLAGS -out:$outDir/$assembly.dll -target:library @tmp.references @tmp.build.sources
  )
}

mkdir -p $outDir

# Tried to magically get projects from Qpid.NET.sln but wrong order for building..
#for project in $(grep ^Project Qpid.NET.sln | sed 's/.*\\\(.*\).csproj.*/\1/'); do
#  Build $project
#done

Build Qpid.Messaging &&
  Build Qpid.Buffer && 
  Build Qpid.Codec && 
  Build Qpid.Common && 
  Build Qpid.Common.Tests && 
  Build Qpid.Client && 
  Build Qpid.Client.Transport.Socket.Blocking &&
  Build Qpid.Client.Tests
