#!/bin/bash
#
#
# Целевой диск
target="/dev/sda"
size="50G"
log_file="/tmp/backaping.log"
workdir="/home/partimag"
compuuid=$(cat /sys/class/dmi/id/product_uuid)
name=$compuuid"_windows.qcow2"
serverSMB="PUT_HERE_SMB_IP"
serverNFS="PUT_HERE_NFS_IP"
sharepass="PUT_HERE_Password"
shareuser="PUT_HERE_Username"
nfsfolder="windows"
smbfolder="Profiles"
# error console
rs() {
    echo "Error code: #$1"
    echo
    # PS1="(DEPLOY) # " exec /bin/bash -i
    sleep 30
    exit 1
}
#ignore breaks
trap : INT TERM HUP
RestoreSystem() {

    diskparts=$(blkid -o device | grep -v -e /sr0 -e loop)
    for prt in $diskparts; do
        mount_point="/mnt/test$prt/"
        mkdir -p "$mount_point"
        mount $prt $mount_point
        test -f $mount_point/Windows/explorer.exe && target=${prt::-1}
        umount "/mnt/test$prt/" -l
    done

    cd /
    echo
    echo "Backup Windows system"
    echo "$name $size"
   # dhclient
    mount.cifs //$serverSMB/$smbfolder $workdir -o user=$shareuser,password=$sharepass,nobrl
    #mount $serverNFS:/$nfsfolder $workdir >$log_file 2>&1
    modprobe nbd max_part=16
    qemu-nbd -d /dev/nbd0 >$log_file 2>&1
    qemu-img create -f qcow2 $workdir/$name $size >$log_file 2>&1
    qemu-nbd --fork --connect=/dev/nbd0 --shared=16 --cache=writeback --detect-zeroes=on --format=qcow2 $workdir/$name >$log_file 2>&1
    #ocs-onthefly -b --nogui -j2 -iui -f $target -d /dev/nbd0 >$log_file 2>&1
    echo "start imaging"
 ocs-onthefly -b --nogui -f $target -d /dev/nbd0 >$log_file 2>&1
    echo "Updating grub to start linux installation"

    parts=$(blkid -o device | grep -v -e /sr0 -e loop)
    for part in $parts; do
        #    part_name=$(basename "$part"
        mount_point="/mnt$part/"
        #Create folder for mounting
        mkdir -p "$mount_point"
        mount $part $mount_point
        test -f $mount_point/boot/grub/grub.cfg && grubpath=$mount_point/boot/grub/grub.cfg
    done
    if test -f $grubpath; then
        sed -i 's/default="0"/default="1"/' $grubpath
    else
        echo "cannot update grub on $grubpath " >>$log_file
    fi
    cp $log_file $workdir
    #PS1="(DEPLOY) # " exec /bin/bash -i
    reboot -f
}
RestoreSystem
