#!/bin/bash
debug=1

function backup_snapshot {
	date=$1
	filename=$2
	if [ `qemu-img info $filename.qcow2 | grep  --count "file format: qcow2"` -eq 1 ]
	then
		echo "Backing up $filename"
		# create the snapshot
		if [ $debug -eq 1 ]
		then
			echo "Creating snapshot"
		fi
		qemu-img snapshot -c $date $filename.qcow2

		#copy the snapshot out
		if [ $debug -eq 1 ]
		then
			echo "Converting snapshot to standalone qcow2 file"
		fi
		qemu-img2 convert -f qcow2 -O qcow2 -s $date $filename.qcow2 $filename-$date.qcow2 

		#delete the old snapshot
		if [ $debug -eq 1 ]
		then
			echo "Deleting snapshot"
		fi
		qemu-img snapshot -d $date $filename.qcow2

	else
		echo "Snapshot backups only support qcow2 files"
	fi
}


date=`date +%d%m%Y`
filename=`echo $1 | sed s/.qcow2//`

backup_snapshot $date $filename

