#!/usr/bin/env bash

build() {
   if [ -d $SAGE_ROOT/devel/$1/ ]; then
      cd $SAGE_ROOT/devel/$1/
      chmod +x ./install
      echo ""
      echo "----------------------------------------------------------"
      echo "sage: Building and installing modified SAGE library files."
      echo ""

      ## install c_lib
      ## we're doing this here instead of setup.py because
      ## it's easier to keep track of whether or not we're 
      ## switching branches, which changes what we do with
      ## the c_lib install
      ##
      ## that's no longer true, but it's easier to just 
      ## keep this here.
      echo ""
      echo "Installing c_lib"
      CUR=`pwd`
      cd "c_lib"
      if [ -n "$SAGE_DEBIAN" ]; then
        SAGE_LOCAL=/usr scons -Q install
      else
        scons -Q install
      fi
      ## make sure c_lib install went okay
      if [ $? -ne 0 ]; then
	  echo "ERROR: There was an error building c_lib."
	  echo ""
	  exit 1
      fi
      cd $CUR

      ./install $SAGE_ROOT
      if [ $? -ne 0 ]; then
         echo "sage: There was an error installing modified $1 library code."
         echo ""
         exit 1
      fi
   #else
      #echo "The directory $SAGE_ROOT/devel/$1/ does not exist."
   fi
}

$SAGE_ROOT/local/bin/sage-env 1>/dev/null

if [ "$1" = "-b" ]; then
    DO_BUILD_ALL=1
    shift
else
    DO_BUILD_ALL=0
fi   


if [ "$1" != "" ]; then
    # make devel/sage point to devel/$1
    cd "$SAGE_ROOT/devel/"
    if [ ! -d "sage-$1" ]; then
        # this will happen a lot because of people (=me) making typos.
        echo "No such branch '$SAGE_ROOT/devel/sage-$1'"
	echo "Use 'sage -clone' to create a new branch."
        exit 1
    fi
    ln -snf "sage-$1" sage
fi

if [ ! -d "$SAGE_ROOT/devel/sage" ]; then
    echo "There is no directory '$SAGE_ROOT/devel/sage'"
    exit 1
fi

if [ $DO_BUILD_ALL = 1 ]; then
   CUR=`pwd`
   cd "$SAGE_ROOT/devel/sage/sage"
   echo "*** TOUCHING ALL CYTHON (.pyx) FILES ***"
   touch */*.pyx */*/*.pyx */*/*/*.pyx */*/*/*/*.pyx */*/*/*/*/*.pyx */*/*/*/*/*.pyx  */*/*/*/*/*/*.pyx 2> /dev/null
   cd ../c_lib
   if [ -n "$SAGE_DEBIAN" ]; then
     SAGE_LOCAL=/usr scons -Q install
   else
     scons -Q install
   fi
   cd ..

   cd "$CUR"
fi

build "sage"
