#!/bin/sh
#
# $Id: cvsup 15788 2007-01-24 13:49:38Z dts12 $
#
TAG=
WO=0
DEST=
TMPDIR=/tmp

if [ "x$1" = "x-u" ]; then
    DEST=$2
    shift 2

    # gnu tar (as of 1.15.1) is unable to create portable tar archives, 
    # especially if long file names (>100 char) are present.
    # star is a better replacement.
    if [ -x /usr/bin/star ]; then
        TAR='/usr/bin/star -Hustar -not -pat=*/.svn/* -c -f'
    elif [ -x /bin/tar ]; then
        TAR="/bin/tar --exclude=.svn -c -f"
        echo "warning: star not available, using (less portable) tar..."
    else
        echo "neither /usr/bin/star nor /bin/tar found."
        exit
    fi
fi

if [ $# -eq 0 ]; then
    DIR=$PWD
else
    if [ $# -ne 1 ]; then
        echo "usage: $0 <working directory>"
        exit
    fi
    DIR=$1
fi

if [ -z ${DIR##*/} ];then
   DIR=${DIR%/*}
fi
SUBD=${DIR##*/}
PARENT=${DIR%*$SUBD}
#echo "$DIR = $PARENT + $SUBD"

if [ ! -d $DIR ]; then
    echo "no such directory '$DIR'"
    exit
fi

if [ ! -d $DIR/.svn ]; then
    echo "'$DIR' has no .svn directory!"
    exit
fi

if [ ! -f $DIR/.svn/entries ]; then
    echo "'$DIR' has no .svn/entries!"
    exit
fi

SVNURL=`svn info $DIR| grep URL|cut -f2 -d " "`
SVNTLD=`echo $SVNURL | sed 's:.*svnroot/net-snmp/\([^/]*\).*:\1:'`
if [ "x$SVNTLD" = "xtrunk" ]; then
   TAG="main"
else
   TAG=`echo $SVNURL | sed 's:.*svnroot/net-snmp/[^/]*/\([^/]*\).*:\1:'`
fi

if [ ! -z $DEST ]; then
    if [ -z $TAG ]; then
        echo "no TAG found in $DIR!"
        exit 1
    fi
fi

COMMAND="svn update -q $SVNURL $DIR"

if [ ! -w $DIR/.svn ]; then
    if [ -O $DIR/.svn ]; then
        WO=1
        echo "Making $DIR writable"
        chmod -R u+w $DIR
    fi
fi

echo "Updating directory $DIR from $TAG..."
echo "$COMMAND"

$COMMAND
rc=$?
if [ $rc -ne 0 ]; then
    echo "svn command returned $?"
fi

if [ $WO -eq 1 ]; then
    echo "Making $DIR read-only"
    chmod -R a-w $DIR
fi

if [ ! -z $DEST ]; then
  if [ $rc -ne 0 ]; then
    echo "skipping upload due to rc $rc from svn command"
    exit $rc
  else
    cd $DIR/..
    #echo $PWD
    DATE=`date +%Y%m%d_%H%M`
    SOURCE=net-snmp-svn-$TAG"_$DATE"
    $TAR $TMPDIR/$SOURCE.tar $SUBD
    rc=$?
    if [ $rc -ne 0 ]; then
      echo "skipping upload due to rc $rc from tar command"
      rm -f $TMPDIR/$SOURCE.tar.gz
      exit $rc
    fi
    gzip -f --best $TMPDIR/$SOURCE.tar
    rc=$?
    if [ $rc -ne 0 ]; then
      echo "skipping upload due to rc $rc from gzip command"
      rm -f $TMPDIR/$SOURCE.tar.gz
      exit $rc
    fi
    scp $TMPDIR/$SOURCE.tar.gz $DEST
    rc=$?
    if [ $rc -ne 0 ]; then
      echo "warning: rc $rc from scp command (tarball in $TMPDIR)"
    else
      rm -f $TMPDIR/$SOURCE.tar.gz
    fi
  fi
fi
