#!/bin/bash
#
# KVM-Snapshot
# If set to 1 compression (gzip) enabled


ENABLE_COMPRESSION="1"
# Retention (in days) of backups to keep
VM_RETENTION="7"
# Space separated list of VMs that you DO NOT want to be backed up.
EXCLUDED_VMS="CentOS_6.6_ori"
# Location backups will be stored. This should be an NFS vol, or iSCSI target or something remote.
BACKUP_DIR="/data/backup/kvm/snapshots"
# Backup server IP
BACKUP_SERVER_IP="10.160.28.31"

DATE=`date +%F`
BZIP="/bin/gzip"
RSYNC="/usr/bin/rsync"

set -e
# Make sure only root can run the script
if [[ $EUID -ne 0 ]]; then
        echo "This script must be run as root" 1>&2
        exit 1
fi

# Get full list of VMs
VMS=`virsh list|sed -n '1!p'|awk {'print $2'}`

# Remove excluded VMS from list
for EXCLUDE in $EXCLUDED_VMS
do
        VMS=`echo $VMS| sed "s/\b$EXCLUDE\b//g"`
done


# Cycle through list of VMs (sans excluded) and pause, snapshot, transfer, compress, and resume.
for BACKUP_VM in $VMS
do
        echo -e "Staring backup for: $BACKUP_VM at ${DATE}"
        [ -d $BACKUP_DIR/$BACKUP_VM/$DATE ] && rm -rf $BACKUP_DIR/$BACKUP_VM/$DATE
        mkdir -p $BACKUP_DIR/$BACKUP_VM/$DATE
        echo "Suspending $BACKUP_VM"
        virsh suspend $BACKUP_VM
        virt-clone --original $BACKUP_VM --auto-clone --file $BACKUP_DIR/$BACKUP_VM/$DATE/$BACKUP_VM.qcow2
        virsh dumpxml $BACKUP_VM-clone > $BACKUP_DIR/$BACKUP_VM/$DATE/$BACKUP_VM.xml
        virsh undefine $BACKUP_VM-clone
        virsh resume $BACKUP_VM
        if [ "$ENABLE_COMPRESSION" -eq "1" ]; then
                echo "Compressing $BACKUP_VM backup"
                tar -czf $BACKUP_DIR/$BACKUP_VM/$DATE.tgz $BACKUP_DIR/$BACKUP_VM/$DATE
                rm -Rf $BACKUP_DIR/$BACKUP_VM/$DATE
        fi
        echo "Searching and deleting old backups per retention: $VM_RETENTION days"
        find /$BACKUP_DIR/$BACKUP_VM/* -mtime +$VM_RETENTION -exec rm {} \;
done

#rsync snapshots to backup machine
${RSYNC} -azvp --delete ${BACKUP_DIR}/ root@${BACKUP_SERVER_IP}:${BACKUP_DIR}/