#!/bin/sh
#
# This script creates an LVM snapshot of a specific file system, mounts it to a 
# directory beneath /snap and starts a backup procedure. After this procedure is
# finished, the snapshot volume is unmounted and removed again.
#
# Last change: 206-10-21 Stefan Tomanek <stefan@pico.ruhr.de>
#                        http://stefans.datenbruch.de/rootserver/

BACKUPSCRIPT="backup-upload.sh"
SNAPDIR="/snap"
SNAPSIZE="200m"

debug() {
    echo $* >&2
}

# This should be something like /dev/mainvol/home
VOL=$1
DIR=$2
MOUNTPOINT=$2

if [ -b "$VOL" ] && [ -d "$MOUNTPOINT" ]; then
    VOLPATH="$(dirname $VOL)"
    VOLNAME="$(basename $VOL)"
else
    debug "Usage: lvmbackup.sh <device> <mountpoint>"
    debug "Example: lvmbackup.sh /dev/mainvolume/home /home/"
    exit 1
fi

# We could also retrieve the data from /proc/mounts
#MOUNTPOINT="$(awk '$1 == "'$VOL'" { print $2}' /etc/fstab)"

cleanup() {
    ABORT=$1
    if [ "$ABORT" -eq "1" ]; then
	debug "Canceling backup procedure and cleaning up..."
    fi
    umount $SNAPDIR/$MOUNTPOINT
    lvremove $SNAPDEV
    exit $ABORT
}
trap "cleanup 1" INT

debug "sycing..."
sync
debug "Creating snapshot of $VOL ($MOUNTPOINT)..."
lvcreate --size $SNAPSIZE --snapshot --name ${VOLNAME}_snap $VOL || exit 1

SNAPDEV="$VOLPATH/${VOLNAME}_snap"

debug "Mounting snapshot volume $SNAPDEV to $SNAPDIR/$MOUNTPOINT..." 
mkdir -p $SNAPDIR/$MOUNTPOINT
echo mount $SNAPDEV $SNAPDIR/$MOUNTPOINT
mount "$SNAPDEV" "$SNAPDIR/$MOUNTPOINT"

debug "Beginning backup run..."
cd $SNAPDIR
BASEDIR=$(echo $MOUNTPOINT | sed 's#^/##' | cut -d/ -f1)
# tar c $BASEDIR | tar tf -
echo $BACKUPSCRIPT $VOLNAME $BASEDIR
$BACKUPSCRIPT $VOLNAME $BASEDIR

debug "Done, unmounting snapshot device from $SNAPDIR/$MOUNTPOINT"
cleanup 0


