#!/bin/bash
#
# Create a backup of the disk image of the virtual machine
#
set -e
LC_ALL=C
export LC_ALL
BACKUP_DIR={{ directory['backup'] }}

log=$(mktemp --tmpdir={{ directory['tmp'] }})
trap "rm -f $log" EXIT TERM INT

set +e
qmpbackup="{{ qmpbackup }} --socket {{ socket_path }} backup --compress --target $BACKUP_DIR --include {{ disk['device'] }}"
$qmpbackup --level auto > $log
RESULT=$?
cat $log
if [ $RESULT -ne 0 ] ; then
  # recover from unfinished previous backup
  if egrep -q 'Partial backup found in.*{{ disk['device']}}.*possible broken backup chain. Execute new full backup' $log ; then
    find $BACKUP_DIR/{{ disk['device'] }} -name '*.partial' -delete
    $qmpbackup --level auto || exit $?
    echo "Recovered from partial backup by removing partial"
  elif egrep -q 'Incremental backup requested but no active bitmap has been found' $log ; then
    find $BACKUP_DIR/{{ disk['device'] }} -name '*.qcow2' -delete
    $qmpbackup --level full || exit $?
    echo "Post take-over cleanup"
  else
    exit $RESULT
  fi
fi
set -e

# as new style backup went fine delete potential old style backup
rm -f $BACKUP_DIR/virtual.qcow2{,.gz}

# cleanup the backup directory from too old backups, especially important after take-over
recent_full=$(find $BACKUP_DIR -type f -name 'FULL-*.qcow2' -exec ls -t1 {} + | head -n1)
if [ x"$recent_full" != x"" ] ; then
  for f in $(find $BACKUP_DIR -type f -name '*qcow2' \! -newer $recent_full) ; do
    if [ "$f" != "$recent_full" ] ; then
      rm -vf $f
    fi
  done
fi

cd $BACKUP_DIR && find -type f ! -name backup.signature -print0 | xargs -0 sha256sum | LC_ALL=C sort -k 66 > backup.signature
