#!/bin/bash

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'] }} {{ 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
tmpdir=$(mktemp -d --tmpdir={{ directory['tmp'] }})
# assure the temporary directory is cleaned up
trap "rm -rf $tmpdir $tmpfile" EXIT TERM INT
cp -a $BACKUP_DIR/* $tmpdir

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

if [ $(find $tmpdir/$disk_type -name 'INC-*' | wc -l | cut -d ' ' -f 1) -gt 0 ] ; then
  {{ qmprebase }} rebase --dir $tmpdir/$disk_type
fi
# assert that restore went well and there is only one file
find $tmpdir/$disk_type -type f -name 'FULL*qcow2' -printf '%f\n' > $tmpfile
if [ $(wc -l $tmpfile | cut -d ' ' -f 1) -ne 1 ] ; then
  echo "Wrong amount of FULL backups"
  cat $tmpfile
  exit 1
fi
cp $tmpdir/$disk_type/* $VM_DIR/virtual.qcow2
