#!/bin/bash
# copyright (C) 2014 FUJITSU LIMITED All Rights Reserved

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# of the License.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  
# 02110-1301, USA.

# check distro
DISTRO=`/usr/lib64/lxcf/lxcf-distro`

# check root
if [ ${EUID:-${UID}} != 0 ]; then
    echo "error: Because you are not root, you cannot execute this command. "
    exit 1
fi

# check args
if [ $# -ne 3 ]; then
	echo "usage : lxcf-snapshot-cluster base-dir src-dir bkup-file"
	exit -1
fi

# set args
BASEDIR=$1
BASENAME=`basename $1`
SRCDIR=$2
SRCNAME=`basename $2`
BKUPDIR=`dirname $3`
if [ x$BKUPDIR == x"." ]; then
	BKUPDIR=$PWD
fi
BKUPNAME=`basename $3`

TMPDIR=`mktemp --tmpdir -d lxcf-snapshot-cluster.XXXXXXX`

# get file tree
pushd $1 >& /dev/null
find -type f > $TMPDIR/$BASENAME.find
popd >& /dev/null

pushd $2 >& /dev/null
find -type f > $TMPDIR/$SRCNAME.find
popd >& /dev/null

# The difference of file tree is examined
diff -u0 $TMPDIR/$BASENAME.find $TMPDIR/$SRCNAME.find | egrep -v '^@@' | tail -n+3 > $TMPDIR/diff.out
egrep '^\+' $TMPDIR/diff.out | sed 's/^\+\./\./g'  > $TMPDIR/add.out
egrep '^\-' $TMPDIR/diff.out | sed 's/^\-\./\./g'  > $TMPDIR/del.out

for i in `cat $TMPDIR/$BASENAME.find`
do
	if [ -e $BASEDIR/$i -a -e $SRCDIR/$i ] ; then
		cmp -s $BASEDIR/$i $SRCDIR/$i >& /dev/null
		if [ $? == 1 ]; then
			echo $i
		fi
	fi
done > $TMPDIR/change.out

# make backup image
pushd $SRCDIR >& /dev/null

cat $TMPDIR/add.out $TMPDIR/change.out | cpio -o --quiet -H ustar | gzip -c > $BKUPDIR/$BKUPNAME 

popd >& /dev/null

# make deletion-file
cp $TMPDIR/del.out $BKUPDIR/$BKUPNAME.rm


rm -rf $TMPDIR

exit 0


