#! /bin/sh 
#
#  Script to help build RTEMS Graphics Toolkit
#
#  $Id: do_it,v 1.13 2010/01/11 04:10:30 joel Exp $
#

BASEDIR=`dirname $0`

GSL=gsl-1.14

######################## Set defaults #############################
# Do we clean after build and install
do_clean="no"

# Do we build GSL support?
do_gsl="yes"

# Are we noisy when running?
verbose="no"
######################## Parse arguments ###########################

usage()
{
cat <<EOF
do_it [options]
  -A - build and install all libraries
  -g - build GSL (default=yes)
  -c - clean after building (default=no)
  -v - verbose

NOTES:
  + Use of each option toggles the setting.  For example, \"-v -v -A -g\"
    results in verbose=no and all steps done except GSL.
  + RTEMS_MAKEFILE_PATH must be set.
  + By default, GSL is built.
EOF
}

fatal()
{
  usage
  exit 1
}

check_status()
{
  if [ $1 -ne 0 ] ; then
    shift
    echo "ERROR: $*" >&2
    exit 1
  fi
}

toggle()
{
  case $1 in
    no)  echo "yes" ;;
    yes) echo "no" ;;
    *)   fatal "Unknown value to toggle ($1)" ;;
  esac
}

while getopts Agcv OPT
do
    case "$OPT" in
      A) do_gsl=yes ;;
      g) do_gsl=`toggle ${do_gsl}` ;;
      c) do_clean=`toggle ${do_clean}` ;;
      v) verbose=`toggle ${verbose}` ;;
      *) fatal;;
    esac
done

shiftcount=`expr $OPTIND - 1`
shift $shiftcount

if [ ${verbose} = yes ] ; then
  echo "GSL Library                    : " ${GSL}
  echo ""
  echo "Clean after install            : " ${do_clean}
  echo ""
fi

######### START OF Consistency checks

if [ X${RTEMS_MAKEFILE_PATH} = X ] ; then
  echo RTEMS_MAKEFILE_PATH not set
  exit 1
fi

# XXX TBD check if enabled before checking if present?
test -d ${GSL}
check_status $? "${GSL} not present"

test -d ${RTEMS_MAKEFILE_PATH}
check_status $? "${RTEMS_MAKEFILE_PATH} not present"

######### END OF Consistency checks

echo "Generating RTEMS_SETTINGS file..."
make -f Makefile.settings clean all
check_status $? Could not generate RTEMS_SETTINGS

source ./RTEMS_SETTINGS

PREFIX=${BSPTOP}

if [ ${verbose} = yes ] ; then
  echo "USING ${PREFIX} for install point!!!"
fi

case ${BSP} in
  pc386) ;; # can be used to turn on detect svgalib supportable on this BSP
  *)
esac

######### Log Directory
LOGDIR=${BASEDIR}/log
if [ ! -d ${LOGDIR} ] ; then
  mkdir ${LOGDIR}
fi
######### 

######### Build and install JPEG
j_gsl()
{
  cd ${GSL}
  CFLAGS="${CPU_CFLAGS}" \
     ./configure --host=${TARGET} --prefix=${PREFIX} \
     --includedir=${PREFIX}/lib/include \
     --disable-shared
  check_status $? Could not configure ${GSL}

  make
  check_status $? Could not make ${GSL}

  make install
  check_status $? Could not make install ${GSL}

  if [ ${do_clean} = yes ] ; then
    make distclean
    check_status $? Could not make distclean ${GSL}
  fi

  cd ..
}

if [ ${do_gsl} = yes ] ; then
  echo "Building ${GSL} ..."
  j_gsl >${LOGDIR}/${TARGET}-${GSL}.log 2>&1
fi

exit 0
