#!/bin/bash
MAILFILE="/tmp/vmmailtxt"
SERVER_NAME=$HOSTNAME  
SENDER=$(whoami)  
USER="noreply"
MAILHEADER="/opt/b2backup/mailheader.txt"
MAILFOOTER="/opt/b2backup/mailfooter.txt"
. ${PWD}/config.txt

export XMLPATH="$VM_XML_PATH"
export SNAP_PATH="$VM_SNAP_PATH"
export KEEP_DAYS="$VM_KEEP_BACKUP_DAYS"

VMS=$(virsh list --all --name)

for vm in $(virsh list --all --name); do
	DATE=$(date +"%Y-%m-%d_%H-%M-%S")
	DEVPATH=$(virsh domblklist $vm | grep -i vda | awk '{print $2}')
	virsh dumpxml --security-info $vm > $XMLPATH/${vm}_${DATE}.xml
	virsh snapshot-create-as --domain $vm ${vm}_temp_$DATE --diskspec vda,file=$SNAP_PATH/${vm}_temp_$DATE.qcow2 --disk-only --quiesce --atomic --no-metadata
	tar czvf $SNAP_PATH/${vm}_$DATE.tar.gz $DEVPATH
	virsh blockcommit $vm vda --active --verbose --pivot
	rm -f $SNAP_PATH/${vm}_temp_$DATE.qcow2
done

for xmldel in $(find $XMLPATH -type f -mtime +$KEEP_DAYS); do
	rm -f $xmldel
done

for snapdel in $(find $SNAP_PATH -type f -mtime +$KEEP_DAYS); do
	rm -f $snapdel
done

echo "VM Backup Complete.  Currently available snapshots:" > $MAILFILE
echo "<pre style='font:monospace'>" >> $MAILFILE
echo "XML:" >> $MAILFILE
echo "$(ls -lh $XMLPATH)" >> $MAILFILE
echo "DISKS:" >> $MAILFILE
echo "$(ls -lh $SNAP_PATH)" >> $MAILFILE



(
	echo "Subject: $VM_EMAILSUB"
	echo "From: $SENDER"
	echo "To: $RECIPIENT"
	cat $MAILHEADER $MAILFILE $MAILFOOTER
) | sendmail -t 

rm $MAILFILE

for var in $(awk -F"=" '{print $1}' ${PWD}/config.txt); do
    unset $var
done