#!/bin/bash

# Designed to fetch an edg release to a particular directory.
# Essentially it hides all the cvs commands from the user.

function Usage () {
  echo ""
  echo -e "Usage: $0  -h | -r release -o output | -l \n"
  echo "-h          :   display help"
  echo "-r release  :   specify the release (cvs) tag."
  echo "-o output   :   specify a directory to put the release in."
  echo "-l          :   list all releases that are available."
  echo ""
  echo Downloads and queries the available tags of the edg-release
  echo module on the marianne web site.
  echo ""
  exit 1
}

function SetupCVS () {

    export CVS_RSH=/tmp/.ssh2222.$$

    echo "#!/bin/sh" > $CVS_RSH
    echo "exec ssh -o 'StrictHostKeyChecking=no' -x -1 -p 2222 \$*" >> $CVS_RSH
    chmod u+x $CVS_RSH

    export CVSROOT=anoncvs@datagrid.in2p3.fr:/cvs
}

function ListTags () {
   cd /tmp
   SetupCVS
   cvs -Q checkout edg-release  
   if [ ! -f edg-release/README ] ; then
      echo "It looks like the CVS server is down."
      echo "datagrid.in2p3.fr"
      echo "Try again later"
      exit 1
   fi
   # Determine which releases are available.
   cvs log edg-release/README \
     | perl -e ' $a = join("",<>) ;
           $a =~ s/^.*symbolic\snames:\s(.*)keyword\ssubstitution:.*$/$1/s ;
           printf("%s",$a) ; ' \
           | sed 's/:.*$//' | tac

}

# Start of the main script.
if [ $# = "0" ] ; then
  Usage
fi

while getopts "hlr:o:" Option 
do
   case $Option in
     h ) Usage ;;
     r ) RELEASE=$OPTARG ;;
     l ) ListTags  ; exit ;;
     o ) OUTPUT=$OPTARG ;;
     * ) Usage  ;;
   esac
done


# Check the output directory is there.
if [ "$OUTPUT" ] && [ ! -d $OUTPUT ] ; then
  echo "Output Directory $OUTPUT does not exist"
  Usage
fi

# Checkout the release
if [ -n "$RELEASE" ] && [ -n "$OUTPUT" ] ; then 
    cd $OUTPUT
    SetupCVS
    cvs -Q checkout -r $RELEASE  edg-release
    if [ $? != "0" ] ; then
       echo "There was a problem checking out release $RELEASE"
    fi
else
    Usage
fi




