#!/bin/bash

# work dir for unpack backup
tmp_dump_path=/var/tmp/one-restore

POSITIONAL=()
while [[ $# -gt 0 ]]; do
key="$1"
    case $key in
        -d|--datastoreid)
            IMAGE_DS="$2"
            shift # past argument
            shift # past value
            ;;
        -n|--name)
            NAME_VM="$2"
            shift # past argument
            shift # past value
            ;;
        *)
            BACKUPID=$1
            shift # past argument
        ;;
    esac
done

if [ -z $BACKUPID ]; then
    echo "Not set BACKUPID"
    exit 1
fi

if [ -z "$IMAGE_DS" ]; then
    IMAGE_DS=$(/usr/bin/onedatastore list | sed '1d' | awk '{if($7 == "img"){want=$1;}}END{print want}')
fi

CHECK_IMAGE_DS=$(/usr/bin/onedatastore list | sed '1d' | awk '{if($1 == '$IMAGE_DS' && $7 == "img"){want=$1;}}END{print want}')
if [ "$CHECK_IMAGE_DS" != "$IMAGE_DS" ]; then
    echo "Datastore $IMAGE_DS not IMAGE type"
    exit 1
fi

function clean {
    rm -rf $work_dir
    if [ -n "$1" ]; then
        if [ -f $tmp_dump_path/$1.lock ]; then
            rm $tmp_dump_path/$1.lock
        fi
    fi
}

function check_vm_state {
    check=1
    LCM_STATE=`/usr/bin/onevm show $1 | grep ^LCM_STATE | cut -d ":" -f 2 | awk '{print $1}'`
    STATE=`/usr/bin/onevm show $1 | grep ^STATE | cut -d ":" -f 2 | awk '{print $1}'`
    case $STATE  in
        ACTIVE )
            if [[ $LCM_STATE  == RUNNING ]]; then
                check=0
            fi
            ;;
        POWEROFF )
            check=0
            ;;
    esac
    return $check
}

# timeout checking
CheckImageTime=4
RestoreLOCK=1

/usr/bin/oneimage show $BACKUPID > /dev/null 2>&1
if [ $? -eq "0" ]; then
    STATE=`/usr/bin/oneimage show $BACKUPID | grep ^STATE | cut -d ":" -f 2 | awk '{print $1}'`
    case $STATE  in
        rdy )
            RestoreLOCK=0
            ;;
        * )
            echo "STATE $STATE not for restore"
            exit 1
            ;;
    esac
else
    echo "Error, check BACKUP $BACKUPID is exist"
    exit 1
fi

if [[ $RestoreLOCK == 0 ]]; then
    mkdir -p $tmp_dump_path
    work_dir=$tmp_dump_path/${BACKUPID}_$(($(date +%s%N)/1000000))
    mkdir $work_dir
    if [ $? -eq "0" ]; then
        SOURCE=`/usr/bin/oneimage show $BACKUPID | grep ^SOURCE | cut -d ":" -f 2 | awk '{print $1}'`
        if [ -f $SOURCE ] && [ $? -eq "0" ]; then
            tar -xzf $SOURCE -C $work_dir
            if [ $? -eq "0" ]; then
                cd $work_dir
                if [ -f $work_dir/vm.template ]; then
                    if ! [ -z "$NAME_VM" ]; then
                        echo "NAME=\"$NAME_VM\"" >> $work_dir/vm.template
                    fi
                    echo "RESTORED_FROM_BACKUP=\"yes\""  >> $work_dir/vm.template

                    bootlist=$(cat $work_dir/boot)
                    bootlist="${bootlist##*( )}"
                    bootlist="${bootlist%%*( )}"

                    disk_num=0
                    for disk_t in $work_dir/*.tmpl; do
                        filename=$(basename -- "$disk_t")
                        imagename_orig=${filename%.*}
                        imagename=${imagename_orig}_`date +%s%N`
                        echo "PATH=\""$work_dir/$imagename_orig"\"" >> $disk_t
                        echo "NAME=\""$imagename"\"" >> $disk_t
                        echo "ALLOW_DELETE_HOOK=\"yes\"" >> $disk_t
                        img_id=$(/usr/bin/oneimage create $disk_t -d $IMAGE_DS | awk '{print $2}')
                        if [ $? -eq "0" ]; then
                            # wait saving...
                            until [[ $(/usr/bin/oneimage show $img_id | grep STATE | awk '{ print $3 }') == "rdy" ]]; do
                                sleep $CheckImageTime
                            done
                        else
                            clean
                            echo "Error create image from template $disk_t"
                            exit 1
                        fi

                        disk_id=`printf '%s\n' "${imagename_orig//disk/}"`
                        target_dev=$(cat ${work_dir}/${imagename_orig}.target)
                        echo "DISK = [" >> $work_dir/vm.template
                        echo "IMAGE_ID = \""${img_id}"\"," >> $work_dir/vm.template
                        echo "DISK_ID = \""${disk_num}"\"," >> $work_dir/vm.template
                        echo "TARGET = \""${target_dev}"\" ]" >> $work_dir/vm.template
                        bootlist=$(echo "${bootlist}" | sed "s/$imagename_orig/disk$disk_num/")
                        ((disk_num++))
                    done
                    tm_mad=$(/usr/bin/onedatastore show $IMAGE_DS  | grep ^TM_MAD=  | cut -d "=" -f 2)
                    tm_mad=${tm_mad#?}
                    tm_mad=${tm_mad%?}
                    echo "SCHED_DS_REQUIREMENTS=\"TM_MAD=${tm_mad}\"" >> $work_dir/vm.template
                    vm_id=$(/usr/bin/onevm create $work_dir/vm.template | awk '{print $2}')
                    if [ $? -eq "0" ]; then
                        if [ -n "$bootlist" ]; then
                            /usr/bin/onevm setboot $vm_id "${bootlist}"
                        fi
                        echo "ID: $vm_id"
                    else
                        clean
                        echo "Backup is wrong format, not found template file"
                        exit 1
                    fi
                else
                    clean
                    echo "Backup is wrong format, not found template file"
                    exit 1
                fi
            else
                clean
                echo "Backup is not .tar.gz archive"
                exit 1
            fi
        else
            clean
            echo "Error, check file $SOURCE exist"
            exit 1
        fi
    else
        clean
        echo "Error create $work_dir"
        exit 1
    fi
fi
clean
