#!/bin/sh -f

#-------------------------------------------------
help ()
#-------------------------------------------------
{
  echo "$1 [make | update] <package> <version> [<root>]"
  echo ""
  echo "    make   : rebuild the package"
  echo "    update : cvs-update the package"
}

#--------------------------------------------------
configure_which ()
#--------------------------------------------------
{
  if test ! "${CMT_WHICH}" = "" ; then
    which_cmd=${CMT_WHICH}; export which_cmd
  else
    which_cmd=`${CMTROOT}/mgr/cmt_which.sh; export which_cmd`
    CMT_WHICH=${which_cmd}; export CMT_WHICH
  fi
}

#--------------------------------------------------
which_file ()
#--------------------------------------------------
{
  ${which_cmd} $1 1>/dev/null 2>/dev/null
  return $?
}

#-------------------------------------------------
#  main ()
#-------------------------------------------------

p=`dirname $0`
p=`dirname $p`

if test "${p}" = "." ; then  # When $0 does not work
  p=`find_file cmt`
  p=`dirname $p`
  p=`dirname $p`
fi

if test "${p}" = "." ; then  # When we are inside cmt
  p=`pwd`
  p=`dirname $p`
fi

CMTROOT=${p}; export CMTROOT

configure_which

test $# -lt 1
if test "$?" = 0 ; then
  help $0
  exit 1
fi

command=$1
shift

root=`dirname $0`
root=`dirname $root`
cmtroot=$root

if test ${cmtroot} = "." ; then
  root=`pwd | sed 's#/tmp_mnt/lal_prod/common#/lal#'`
  root=`dirname $root`
  cmtroot=$root
fi

root=`dirname $root`
root=`dirname $root`

if test -d "/virgoApp" ; then
  root=/virgoApp
fi

PATH=${PATH}:/usr/local1/bin

package=$1
version=$2
ppath=$3

if test "$ppath" = "" ; then
  p=${root}/${package}/${version}/mgr
else
  c=`echo ${ppath} | sed 's#^[/].*#/#'`
  if test "$c" = "/" ; then
    p=${ppath}/${package}/${version}/mgr
  else
    p=${root}/${ppath}/${package}/${version}/mgr
  fi
fi

cd $p

if test "$?" = 1 ; then
  echo "Bad path specification $p"
  exit 1
fi

if test ! -f setup.csh ; then
  ${cmtroot}/mgr/cmt config
fi


if test ${command} = "make" ; then

  extra=
  if test ${package} = "cmt" ; then
    which_file gcc
    if test "$?" = 1 ; then
      extra="cc=cc"
    fi
  fi
 
  csh -c "(source setup.csh; make ${extra})"

else

  if test ${command} = "update" ; then

    cd ../
    cvs update

  else

    help $0

  fi

fi



