#!/usr/bin/env bash
#-----------------------------------------------------------------------
#  usage:   cdfopr/scripts/checkout_patches version [debug]
#
#  example: 
#  --------
#           cdfopr/scripts/checkout_patches 5.3.1_physics
#
#  will use patches file Release/patches/5.3.1_physics.patches
#-----------------------------------------------------------------------
prefix="" ; if [ .$2 != . ] ; then prefix=echo ; fi

if [ .$1 != "." ] ; then x=`echo $1 | awk -F / '{print $2}'`
else                     x=""
fi

if [ ."$x" == "." ] ; then patch_file=Release/patches/$1.patches
else                  patch_file=$1
fi
#-----------------------------------------------------------------------
#  call: list_of_patches patch_file
#-----------------------------------------------------------------------
list_of_patches() {
    cat $1 | \
    awk '{ if (substr($1,1,1) != "#") print $1}' | sed 's#/.*##' | uniq
}

#-----------------------------------------------------------------------
# call: checkout_patches patch_file
#-----------------------------------------------------------------------
checkout_patches () {
    patch_file=$1
    list=`list_of_patches $patch_file`
#-----------------------------------------------------------------------
# check out default for this release versions of the packages involved
# assume development is available
#-----------------------------------------------------------------------
    for package in $list ; do
        echo --- package=$package
	if [ ! -d $package ] ; then 
	    if [ -d ~cdfsoft/dist/releases/development/$package/CVS/Root ] ; then 
              repository=`cat ~cdfsoft/dist/releases/development/$package/CVS/Root`
	      $prefix addpkg -d $repository $package 
	    elif [ -d $CDFSOFT2_DIR/$package ] ; then 
	      $prefix addpkg $package 
	    else
	      echo Warning - $package is not in the release, using '"'cvs co'"' instead of '"'addpkg'"'
	      $prefix cvs co $package 
            fi
	fi
    done
#------------------------------------------------------------------------------
# proceed with the non-defaults, do `cvs co` for them (default versions
# skip empty lines and default versions
#------------------------------------------------------------------------------
tmp=$USER.$$
# echo --- proceed with the non-defaults, patch_file=$patch_file

if [ -f $tmp ] ; then rm $tmp ; fi
  cat $patch_file | awk \
   '{ 
      if ((substr($0,1,1) != "#") && ($1 != "") && ($2 == "-r")) {
          loc=index($1,"/");
          if (loc > 1) {
            package=substr($1,1,loc-1);
          }
          else {
            package = $1
          }
          printf "cvs -d `cat %s/CVS/Root` co -r %s %s\n", package, $3, $1 
      }
    }' > $tmp ; $prefix source $tmp ; rm $tmp
}

echo checkout_patches $patch_file
if [ .$1 != "." ] ; then  checkout_patches $patch_file ; fi
#------------------------------------------------------------------------------
