#!/bin/sh
#    Copyright (c) 2014-2016 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    Description:
#     restore host images from snapshot images.
#		1) partition
#		2) copy images from snapshot partition
#

SNAPSHOT_PARTITION=/dev/sdb2
SNAPSHOT_DIR=/SNAPSHOW
SNAPSHOT_DIR_VM=${SNAPSHOT_DIR}/VM
SNAPSHOT_DIR_HOST=${SNAPSHOT_DIR}/HOST
SNAPSHOT_DATA_DIR=${SNAPSHOT_DIR}/.snapshot
SNAPSHOT_VERSION_FILE=${SNAPSHOT_DATA_DIR}/snapshot_version 
SNAPSHOT_HOST_DONE_FILE=${SNAPSHOT_DATA_DIR}/host_snapshot_completed 
SNAPSHOT_VM_DONE_FILE=${SNAPSHOT_DATA_DIR}/vm_snapshot_completed 

# main 


	for snap in `mount | cut -d" " -f3 | grep "$SNAPSHOT_DIR"`; do umount $SNAPSHOT_DIR; done
	if [ $? -ne 0 ]; then
		echo "Error in unmounting Snaspshot partition"
		exit 1
	fi


	mkdir -p $SNAPSHOT_DIR
	if [ $? -ne 0 ]; then
		echo "Error in creating mount point"
		exit 1
	fi

	mount $SNAPSHOT_PARTITION   $SNAPSHOT_DIR
	if [ $? -ne 0 ]; then
		echo "Error in mounting Snaspshot partition"
		exit 1
	fi

	if [ -f $SNAPSHOT_VERSION_FILE -a -f $SNAPSHOT_HOST_DONE_FILE -a -f $SNAPSHOT_VM_DONE_FILE ]; then
		echo "==============================================================="
		echo "SNAPSHOT_RESTORE: Restoring from the following Snapshot images:"
		echo "==============================================================="
		cat $SNAPSHOT_DATA_DIR/snapshot_version
		echo "==============================================================="
	else
		echo "Error in getting the Snapshot image version "
		exit 1
	fi

	umount  $SNAPSHOT_DIR
	if [ $? -ne 0 ]; then
		echo "Error in unmounting Snaspshot partition"
		exit 1
	fi

	rmdir  $SNAPSHOT_DIR
	if [ $? -ne 0 ]; then
		echo "Error in deleting mount directory"
		exit 1
	fi


echo "========================================================="
echo "SNAPSHOT_RESTORE: Restoring HOST from the Snapshot Images"
echo "========================================================="
./image_snapshot_restore_host.sh

echo "======================================================="
echo "SNAPSHOT_RESTORE: Restoring VM from the Snapshot Images"
echo "======================================================="
./image_snapshot_restore_vm.sh

#if ONIE set nos_bootcmd
REL=`uname -r`
case $REL in
	*"onie"* )
	bootenv nos_bootcmd 'setenv prt 3;ext4load scsi 0:${prt} 0x1000000 /boot/vmlinuz;zboot 0x1000000'
	if [ $? -ne 0 ]; then
		echo "Error: Unable to set bootenv:" "$?"
	fi
	;;
	*)
		;;
esac

echo
echo
echo "SNAPSHOT_RESTORE: Please reboot the system."

#end
