#!/bin/bash

set -e

VM_DIR={{ directory['srv'] }}
BACKUP_DIR={{ directory['backup'] }}
LC_ALL=C
export LC_ALL
umask 077

write_backup_proof () {
  cd {{ directory['backup'] }}
  find -type f ! -name backup.signature ! -wholename "./rdiff-backup-data/*" -print0 | xargs -0 sha256sum  | LC_ALL=C sort -k 66 > {{ directory['srv'] }}/proof.signature
  diff -ruw {{ directory['backup'] }}/backup.signature {{ directory['srv'] }}/proof.signature > {{ directory['srv'] }}/backup.diff
}

# For now we just make the diff before 
write_backup_proof

tmpfile=$(mktemp --tmpdir={{ directory['tmp'] }})
# use temporary space inside of the partition, as it can be quite big
# assure the temporary directory is cleaned up
trap "rm -rf $tmpdir $tmpfile" EXIT TERM INT

if [ -d $BACKUP_DIR/ide0-hd0 ] ; then
  disk_type="ide0-hd0"
elif [ -d $BACKUP_DIR/virtio0 ] ; then
  disk_type=virtio0
else
  echo "Unsupported disk type"
  exit 1
fi

rm -f $VM_DIR/virtual.qcow2
{{ qmprestore }} merge --dir $BACKUP_DIR/$disk_type --target $VM_DIR/virtual.qcow2
