#!/bin/bash
#
# This file is part of vbackup.
#
# vbackup 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; either version 2 of the License, or
# (at your option) any later version.
#
# vbackup 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 vbackup; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
#
# $Id: xfsdump 1905 2009-05-23 13:06:49Z v13 $
#
# Description
#
#

NAME="xfsdump"
VERSION="$PACKAGE_VERSION"
DESC="XFS backup using xfsdump"
LICENSE="GPLv2"
COPYRIGHT="Copyright (c) 2006-2007 Stefanos Harhalakis"
CONTACT="v13@v13.gr"

# Display help
do_help()
{
	cat << _END
Configuration options:
	LEVEL		The backup level (0-9) (required)
	PARTITIONS	The partitions to backup. This is a space separated
			list of partitions. They can be identified by
			mountpoint or by device name (required)
	MEDLABEL	Media label to be passed to xfsdump (i.e. hostname)	
	DESTDIR		The directory to backup to (required)
_END
	if [ -z "$XFSDUMP" ] ; then
		cat << _END

 !! This method is DISABLED because xfsdump was not found
_END
	fi
}

# Check configuration
# return: 0: ok, 1: error
do_check_conf()
{
	local	tmp

	[ -z "$XFSDUMP" ] && h_error "xfsdump was not found" && return 1

	[ -z "$LEVEL" ] && h_error "Missing LEVEL" && return 1
	[ -z "$PARTITIONS" ] && h_error "Missing PARTITIONS" && return 1
	[ -z "$DESTDIR" ] && h_error "Missing DESTDIR" && return 1

	tmp=`expr $LEVEL + 1 >/dev/null 2>&1 || echo koko`

	[ "$tmp" = "koko" ] && h_error "LEVEL must be a number" && return 1

	if [ "$LEVEL" -lt 0 ] || [ "$LEVEL" -gt 9 ] ; then
		h_error "LEVEL must be in the range 0-9"
		return 1
	fi

	return 0
}

# Do the dump
#	$1:	Mount point / partition
#	$2:	Filename
do_dump()
{
	local	T_M

	T_M="-M '$MEDLABEL'"

	if h_is_true $COMPRESS ; then
		FN="$2.gz"
		h_msg 6 "Dumping $1 to $FN"
		$XFSDUMP -l $LEVEL $T_M -L "$1" - "$1" | gzip > "$FN"
		if ! [ "$?" -eq 0 ] ; then
			return 1
		fi
	else
		h_msg 6 "Dumping $1 to $2"
		if ! $XFSDUMP -l $LEVEL $T_M -L "$1" -f "$2" "$1" ; then
			return 1
		fi
	fi

	return 0
}

# Do backup
do_run()
{
	if [ "x$ABORT" = "x1" ] ; then
		return 0
	fi

	if [ -z "$XFSDUMP" ] ; then
		h_error "xfsdump was not found"
		return 1
	fi

	for part in $PARTITIONS ; do
		FN=`echo "${part}" | sed s,^/,, | sed s,/,.,g`
		if [ "$FN" = "root" ] ; then
			# Worst case scenario
			# In case someone crazy enough mounted /root to a
			# partition of its own
			$FN="root."
		fi
		if [ -z "$FN" ] ; then
			FN="root"
		fi
		if ! do_dump "$part" "$DESTDIR/$FN" ; then
			h_error "Backup of $part failed"
			return 1
		fi
	done
}

