#!/bin/bash

# log contents
address="`sqlite3 /unas/etc/vmbackup/vmbackup.db \"SELECT HST_Host FROM T_Host where HST_No=$HSTNO;\"`"
port="`sqlite3 /unas/etc/vmbackup/vmbackup.db \"SELECT HST_Port FROM T_Host where HST_No=$HSTNO;\"`"
action=2
step=1
result=0
content="Restore start"
reason=
write_log(){
    sqlite3 /unas/etc/vmbackup/vmbackup.db "INSERT INTO t_log( log_time, hst_address, hst_port, vm_name, log_action, log_step, log_result, log_content, log_reason)VALUES( DATETIME(CURRENT_TIMESTAMP, 'localtime'), \"$address\", \"$port\", \"$VM\", \"$action\", \"$step\", \"$result\", \"$content\", \"$reason\");"
}

run_dir=/run/vmbackup/restore/$id
restore_id=`echo -e restore jobid=$JOBID client=$CLIENT \\\\n5\\\\nmark *\\\\ndone\\\\nyes\\\\n | bconsole | grep -e 'Job queued\. JobId=[1-9][0-9]*' | awk -F = '{print $2}'`

get_hst(){
    export GOVC_USERNAME="`sqlite3 /unas/etc/vmbackup/vmbackup.db \"SELECT HST_User FROM T_Host where HST_No=$HSTNO;\"`"
    export GOVC_PASSWORD="`sqlite3 /unas/etc/vmbackup/vmbackup.db \"SELECT HST_Password FROM T_Host where HST_No=$HSTNO;\"`"
    export GOVC_URL="`sqlite3 /unas/etc/vmbackup/vmbackup.db \"SELECT HST_Host FROM T_Host where HST_No=$HSTNO;\"`":"`sqlite3 /unas/etc/vmbackup/vmbackup.db \"SELECT HST_Port FROM T_Host where HST_No=$HSTNO;\"`"
    export GOVC_INSECURE=true

    export GOVC_DATACENTER="`/unas/sbin/vmbackup/engine vm.info '$VM' | grep -w '^  Path: ' | awk -F '/' '{print $2}'`"
}

if [ -n "$restore_id" ];then
    write_log

    status=`echo wait jobid=$restore_id | bconsole | grep JobStatus=`
    if echo $status | grep -q 'JobStatus=OK (T)';then
        step=99
        content="Restore completed"
        result=0
        write_log
        if [ "$POWER"z == "1"z ];then
            get_hst
            /unas/sbin/vmbackup/engine vm.power -on "$VM"
        fi
    else
        step=84
        content="Restore failed"
        reason="Please make sure the vm is poweroff and has no snapshots."
        result=1
        write_log
    fi
else
    reason="Failed to create restore job"
    content="Failed to create restore job"
    result=1
    write_log
fi

rm -rf $run_dir
