#!/bin/sh
host=$1; shift;
vmHost=$1; shift;

# How many Pings send to check the Default Gateway
PINGCOUNT="5"
# When should check_icmp gets faulty, see check_icmp --help
FAULT="5000,100%"
# Timeout for ping checks
TIMEOUT="30"

sshPath="/usr/bin/ssh"
DumpPreUserCmd="$sshPath -q -x -l root ${host} /usr/share/backuppc-helper/lvm_pre_backup ${vmHost}"
DumpPostUserCmd="$sshPath -q -x -l root ${host} /usr/share/backuppc-helper/lvm_post_backup ${vmHost}"

if [ -f /etc/default/backuppc-helper ]
then
        . /etc/default/backuppc-helper
        if [ -z "$VOL" ]
        then
                echo "#### WARNING ####"
                echo "VOL in /etc/default/backuppc-helper not set!"
                echo "#################"
                exit 0
        fi
else
        echo "#### WARNING ####"
        echo "/etc/default/backuppc-helper is missing!"
        echo "#################"
        exit 0
fi

if [ `mount | grep ${vmHost} | wc -l` -gt "0" ] ; then
        echo "#### WARNING ####"
        echo "/dev/${VOL}/${vmHost}-disk already mounted!"
        echo "#################"
        exit 0
fi

# is the check_icmp binary there?
if [ ! -e /usr/lib/nagios/plugins/check_icmp ]; then 
        echo "#### ERROR ####"
        echo "check_icmp not found! Is nagios-plugins-basic installed?"
        echo "###############"
        exit 1
fi

# check
/usr/lib/nagios/plugins/check_icmp -n ${PINGCOUNT} -t ${TIMEOUT} -w ${FAULT} -c ${FAULT} -H ${host} > /dev/null || unreach="true"
if [ ${unreach} ] ; then
	echo "#### ERROR ####"
	echo "$host not reachable!"
	echo "###############"
	exit 1
fi

# create directory
mkdir -p /mnt/${vmHost}

# mount target fs
mount /dev/${VOL}/${vmHost}-disk /mnt/${vmHost}

# mount snapshot of source fs on remote system
$DumpPreUserCmd

# sync remote filesystem with local once
rsync -az --numeric-ids --delete root@${host}:/mnt/${vmHost}/ /mnt/${vmHost}/
rsync -az --numeric-ids --delete root@${host}:/etc/xen/${vmHost}* /etc/xen/

# umount snapshot of source fs on remote system
$DumpPostUserCmd

# umount target fs
umount /mnt/${vmHost}