#!/bin/bash

# This file is part of MEGAlib.
# Copyright (C) by Andreas Zoglauer.
#
# Please see the MEGAlib software license and documentation for more informations.


FOLDER=${MEGALIB}
REPONAME="MEGAlib"


#FOLDER=~/tmp/MEGAlib

cd ${FOLDER}

# Start with determining if we have a cvs or svn repository:
if ( `test -d ${FOLDER}/.svn` ); then
  URL=`svn info | grep "URL" | awk -F": " '{ print $2 }'`
  #echo ${URL}
  if [[ ${URL} == */trunk ]] ; then
    #echo "In trunk"
    svn update
  elif [[ ${URL} == */${REPONAME}/branches/Version_* ]] ; then
    #echo "In branch"
    SubURL=`echo ${URL} | awk -F"/Version" '{ print $1 }'`
    Branches=`svn list $SubURL | grep "Version" | sed 's/\///g' | sort -R | sort -r -n`
    Branches=`echo ${Branches} | awk -F" " '{ print $1 }'`
    #echo ${Branches}
    svn switch ${SubURL}/${Branches}
  fi
elif ( `test -d ${FOLDER}/CVS` ); then
  Sticky=`cvs status -v src/global/misc/src/MGlobal.cxx | grep "Sticky Tag" | grep "branch"`
  SERVER=`cat CVS/Root`

  if [[ ${Sticky} == *${REPONAME}* ]] ; then
    #echo "In branch"

    if ( `test -f src/global/misc/src/MGlobal.cxx` ); then
      Branches1=`cvs status -v src/global/misc/src/MGlobal.cxx | grep ${REPONAME}_  | awk -F" " '{ print $1 }'`
    fi
    if ( `test -f config/Version.txt` ); then
      Branches2=`cvs status -v config/Version.txt | grep ${REPONAME}_  | awk -F" " '{ print $1 }'`
    fi
    AllBranches="${Branches1} ${Branches2}"
    AllBranches=`echo ${AllBranches} | tr sort -R | sort -r -n`
    for b in ${AllBranches}; do
      if [[ ${b} == ${REPONAME}* ]] ; then
        Branches="${Branches} ${b}"
      fi
    done
    Branches=`echo ${Branches} | awk -F" " '{ print $1 }'`
    cvs -d ${SERVER} update -d -P -r ${Branches} 
  else
    #echo "In trunk"
    cvs -d ${SERVER} update -d -P -r HEAD
  fi
  
fi

exit 0;
