#!/bin/sh
#
# Copyright (c) Citrix Systems 2008. All rights reserved.
#

set -e
set -x

# Restore a backup to the other partition
. /etc/xensource-inventory
DEVICE=$BACKUP_PARTITION

if [ -z "$DEVICE" ]
then
     # Don't know where to put the backup!
     exit 2
fi

# Preserve the partition label when reformatting
LABEL=$(e2label "${DEVICE}" 2>/dev/null || echo "")
mkfs.ext3 -q -L "${LABEL}" "${DEVICE}"

TMP=`mktemp -d`

error () {
      trap - EXIT ERR
      umount $TMP || true
      rmdir $TMP || true
}

trap error EXIT ERR

mount $DEVICE $TMP
tar -C $TMP -xzp

# The dom0 partition layout changed between 6.x and 7.x and restoring backups
# from the old partition layout does not work in some cases so fail the
# restore operation.

CUR_VER="$PRODUCT_VERSION"
. "$TMP/etc/xensource-inventory"
PREV_VER="$PRODUCT_VERSION"

if [ "${CUR_VER%%.*}" -ge 7 -a "${PREV_VER%%.*}" -lt 7 ]; then
    echo "Cannot restore backup created with a different partition layout."
    exit 1
fi

# The installer checks for this file when looking for a backup partition.
touch $TMP/.xen-backup-partition

