#!/bin/bash
STARTDIR=/home/SMCDev/SMC/timelimit
PROGVER=timelimit-1.8
PROGFILE=$STARTDIR/$PROGVER.tar.gz
ARMDIR=$STARTDIR/armbuild
ARMOUT=$STARTDIR/armoutput
ARMLOG=$STARTDIR/arm.log
ARMTCTEMP=$STARTDIR/armtctemp
NATIVEDIR=$STARTDIR/nativebuild
NATIVEOUT=$STARTDIR/nativeoutput
NATIVELOG=$STARTDIR/native.log
XTC=$STARTDIR/armtoolchain

BUILD=1
CLEAN=0
REBUILD=0
NATIVE=0
ARM=1
ARCHSPEC=1

while [ -n "$1" ]
do
  if [ "$1" = "clean" ]
  then
    BUILD=0
    REBUILD=0
    CLEAN=1
  elif [ "$1" = "rebuild" ]
  then
    BUILD=0
    REBUILD=1
    CLEAN=0
  #elif [ "$1" = "arm" ]
  #then
  #  if [ $ARCHSPEC -eq 0 ]
  #  then
  #    ARCHSPEC=1
  #    NATIVE=0
  #  fi
  #  ARM=1
  #elif [ "$1" = "native" ]
  #then
  #  if [ $ARCHSPEC -eq 0 ]
  #  then
  #    ARCHSPEC=1
  #    ARM=0
  #  fi
  #  NATIVE=1
  #else
  #  echo "Unexpected option: $1"
  #  exit 1
  fi
  shift
done

cd $STARTDIR

if [ ! -L $XTC ]
then
  echo "Missing link to toolchain at $XTC"
  exit 1
fi

if [ ! -f $PROGFILE ]
then
  echo "Missing archive file: $PROGFILE"
  exit 1
fi

if [ \( $CLEAN -ne 0 \) -o \( $REBUILD -ne 0 \) ]
then
  if [ \( $ARCHSPEC -eq 0 \) -o \( $NATIVE -ne 0 \) ]
  then
    echo "Cleaning native files"
    rm -rf $NATIVEDIR $NATIVEOUT
  fi
  if [ \( $ARCHSPEC -eq 0 \) -o \( $ARM -ne 0 \) ]
  then
    echo "Cleaning ARM files"
    rm -rf $ARMDIR $ARMOUT
  fi
fi

if [ \( $BUILD -ne 0 \) -o \( $REBUILD -ne 0 \) ]
then

  if [ \( $ARCHSPEC -eq 0 \) -o \( $NATIVE -ne 0 \) ]
  then
    echo "*"
    echo "Making native build"
    echo "*"
    if [ ! -d $NATIVEDIR ]; then mkdir $NATIVEDIR ; fi
    if [ ! -d $NATIVEOUT ]; then mkdir $NATIVEOUT ; fi
    cd $NATIVEDIR
    echo "*"
    echo "* Performing initial native configuration"
    echo "*"
    ./configure --prefix=$NATIVEOUT 2>&1 | tee $NATIVELOG
    echo "*"
    echo "* Building native $PROGVER"
    echo "*"
    make 2>&1 | tee -a $NATIVELOG
    echo "*"
    echo "* Installing native $PROGVER"
    echo "*"
    make install 2>&1 | tee -a $NATIVELOG
  fi

  if [ \( $ARCHSPEC -eq 0 \) -o \( $ARM -ne 0 \) ]
  then
    echo "*"
    echo "Making ARM build"
    echo "*"
    if [ ! -d $ARMDIR ]; then ( mkdir $ARMDIR ; cd $ARMDIR ; tar xvf $PROGFILE --strip-components=1 ) fi
    if [ ! -d $ARMOUT ]; then mkdir $ARMOUT ; fi
    cd $ARMDIR
    (
        echo "*"
        echo "* Performing initial ARM configuration"
        echo "*"
	export PATH="$XTC/usr/bin:$PATH"
        export LIBRARY_PATH=$XTC/usr/lib
        export CPATH="$XTC/usr/include"
	cd $ARMDIR
        export CC=armv7l-timesys-linux-uclibcgnueabi-gcc
        ./configure --prefix=$ARMOUT --host=armv7l-timesys-linux-uclibcgnueabi --build=i686-pc-linux-gnu
        echo "*"
        echo "* Building $PROGVER for ARM"
        echo "*"
	make
	#echo "*"
	#echo "* Installing $PROGVER"
	#echo "*"
        #make install
      ) 2>&1 | tee $ARMLOG
  fi

fi

