#!/bin/bash
#
# usage: get-orig-source <original package name> <branch> <version of rc>
#        e.g.: get-orig-source VolumeDIST rc-1-5-6 ~rc1
#
package=$1
branch=$2
rcversion=$3

REMOTECVSROOT=:pserver:anonymous@mgl1.scripps.edu:2401/opt/cvs
CVS=/usr/bin/cvs
MGLTOOLSCVS=../../mgltools-cvs

# Expected by svn-buildpackage as 'tarballs'
TARDIR=../tarballs

PREFIX="mgltools-"
if [ "$package" == "AutoDockToolsDIST" ]; then
  PREFIX=""
fi
DEBPACKAGE=$PREFIX`echo $package|sed "s/DIST//g"| tr 'A'-'Z' 'a'-'z'`

# do some stuff
echo "I: get $package (-> $DEBPACKAGE) from branch $branch"

loginDone=`grep "$REMOTECVSROOT" ~/.cvspass|wc -l`
if [ "$loginDone" == "0" ]; then
  $CVS -d$REMOTECVSROOT login
fi

if [ -d "$MGLTOOLSCVS" ]; then
  echo "I: cvs directory already available"
else
  echo "I: create directory '$MGLTOOLSCVS' to store new CVS checkout"
  mkdir "$MGLTOOLSCVS"
fi

if [ -d $MGLTOOLSCVS/$package ]; then
  echo "I: ... checkout already done"
  if [ -r "$MGLTOOLSCVS/$package/CVS/Tag" ]; then
    echo "W:     check whether this is the correct tag: `cat $MGLTOOLSCVS/$package/CVS/Tag`"
  else
    echo "W:     no tag file found. You may be working on the trunk, not on the release branch. Is that what you want?"
  fi
  sleep 3
  (cd $MGLTOOLSCVS/$package && $CVS -z3 update -d)
else
  echo "I: ... now performing checkout"
  (cd "$MGLTOOLSCVS" &&  $CVS -z3 -d$REMOTECVSROOT co -r $branch $package)
fi

version=`echo $branch|sed "s/rc-//g"|tr '-' '.'`

DATE=`date +"%Y%m%d"`
if [ -f $MGLTOOLSCVS/build-for-date ]; then
  DATE=`cat $MGLTOOLSCVS/build-for-date`
fi
if [ -z ${rcversion} ]; then
  echo "I: no rc but real release"
  origFilename=${DEBPACKAGE}_${version}${rcversion}.orig.tar.gz
  origDirname=${DEBPACKAGE}-${version}${rcversion}
else
  origFilename=${DEBPACKAGE}_${version}${rcversion}~cvs.${DATE}.orig.tar.gz
  origDirname=${DEBPACKAGE}-${version}${rcversion}~cvs.${DATE}
fi

echo "I: Filename of origFile: $origFilename"

cd "$MGLTOOLSCVS"
if [ -d "$TARDIR" ]; then
  echo "I: directory for orig tarballs already available"
else
  echo "I: creating directory for irog tarballs: '$TARDIR'"
  mkdir "$TARDIR"
fi

if [ -f "$TARDIR"/"$origFilename" ]; then
  echo "I: delete old file '$origFilename' "
  rm "$TARDIR"/"$origFilename"
fi
if [ -n "$origDirname" -a -d "$origDirname" ]; then
  echo "W: Amazingly, temporary directory name '$origDirname' is already existing. Stop this script if this shall not be removed -- within 3 seconds."
  sleep 3
  rm -r "$origDirname"
fi

echo "I: remove some files in '$package' "
cd $package
echo "I: ... *.dll "
find . -name *.dll -a -type f| xargs -r rm -rf
cd ..

echo "I: Temporarily renaming and taring $package "
echo " --> $MGLTOOLSCVS/$TARDIR/$origFilename"
mv "$package" "$origDirname"

echo -n "I: Number of files in package: "
GZIP=-9 tar --exclude CVS -czvf "$TARDIR/$origFilename" "$origDirname" | wc -l
mv "$origDirname" "$package"
echo "I: done"

