#!/bin/bash

# Copyright (C) 2010, 2011, 2012 Oregon State University
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

set -e

. common.sh

debug set -x

# If the target device is not a real block device we'll first losetup it.
# This is needed for file disks.
if [ ! -b $blockdev ]; then
    ORIGINAL_BLOCKDEV=$blockdev
    blockdev=$($LOSETUP -sf $blockdev)
    CLEANUP+=("$LOSETUP -d $blockdev")
fi

TARGET=`mktemp -d` || exit 1
CLEANUP+=("rmdir $TARGET")
DUMPDIR=`mktemp -d` || exit 1
CLEANUP+=("rm -rf $DUMPDIR")

if [ ! "${NOMOUNT}" = "yes" ] ; then
    format_disk0 $blockdev
    filesystem_dev=$(map_disk0 $blockdev)
    CLEANUP+=("unmap_disk0 $blockdev")
    root_dev=$(map_partition $filesystem_dev root)
    boot_dev=$(map_partition $filesystem_dev boot)
    swap_dev=$(map_partition $filesystem_dev swap)

    mkfs_disk0
    root_uuid="$($VOL_ID $root_dev)"
    [ -n "$boot_dev" ] && boot_uuid="$($VOL_ID $boot_dev)"
    [ -n "$swap_dev" ] && swap_uuid="$($VOL_ID $swap_dev)"

    mount_disk0 $TARGET
fi

# import dumps from tar file
( cd $DUMPDIR; tar -xf - )

if [ "${NOMOUNT}" = "yes" ] ; then
    ( $QEMU_IMG convert ${DUMPDIR}/disk.img -O host_device ${blockdev} )
else
    # clean up any previous restore runs
    rm -rf /tmp/rst*
    ( cd $TARGET ; restore -r -y -f ${DUMPDIR}/root.dump )
    if [ -n "${boot_dev}" ] ; then
        ( cd ${TARGET}/boot ; restore -r -y -f ${DUMPDIR}/boot.dump )
    fi

    setup_fstab $TARGET

    if [ "${INSTANCE_HV_serial_console}" = "True" ] ; then
        setup_console $TARGET
    fi

    rm -f $TARGET/etc/udev/rules.d/z*_persistent-net.rules

    if [ -n "$CUSTOMIZE_DIR" -a -d "$CUSTOMIZE_DIR" -a -x "$CUSTOMIZE_DIR/grub" ] ; then
        TARGET=$TARGET
        BLOCKDEV=$blockdev
        ROOT_DEV=$root_dev
        BOOT_DEV=$boot_dev
        IMPORT_SCRIPT="1"
        export TARGET SUITE BLOCKDEV ROOT_DEV BOOT_DEV IMPORT_SCRIPT
        # Install grub since we're not deploying via qemu-img
        ${CUSTOMIZE_DIR}/grub
    fi
fi

# execute cleanups
cleanup
trap - EXIT

exit 0
