#!/bin/bash

set -e
#set -v

LIVE_SNIPPET_DIR=/opt/aus2/incoming/3
BACKUP_DIR=/opt/aus2/snippets/backup
STAGING_DIR=/opt/aus2/snippets/staging

WC=/usr/bin/wc
DATE=/bin/date
TAR=/bin/tar
SED=/bin/sed
GREP=/bin/grep

if test -z $1; then 
   echo Usage: $0 [snippet-directory-to-sync-in from $STAGING_DIR]
   exit 1
fi

newSnippetDir=`echo $1 | $SED -e 's/\///'g`

if ! test -d $STAGING_DIR/$newSnippetDir; then
   echo Usage: $0 [snippet-directory-to-sync-in from $STAGING_DIR]
   exit 1
fi

currentDate=`$DATE +%Y%m%d`

## We use the shell's expansion capabilites to get a list of other snippet
## directories we may have pushed today... kinda lame, but it works.

pushd $BACKUP_DIR > /dev/null
preDirCount=`echo $currentDate-?-pre-* | $GREP -v \? | $WC -w`
popd > /dev/null

## Increment the count by one, for the new snippet backup directory we're
## about to create
let nextPreDirCount=$preDirCount+1
#echo $nextPreDirCount
backupDirName=$currentDate-$nextPreDirCount-pre-$1

pushd $LIVE_SNIPPET_DIR > /dev/null
echo Running $TAR cfvj $BACKUP_DIR/$backupDirName.tar.bz2 . 
$TAR cfj $BACKUP_DIR/$backupDirName.tar.bz2 . 
popd > /dev/null

exit 0
