#!/bin/bash
SOURCE_DISK_PATH=$1
DEST_DISK_PATH=$2
SPEED=$3
TO_SSH_PORT=$4
TO_IP=$5
LOGFILE=$6
ACTUAL_TRANSFER_LOG=$7
DISABLE_GZIP=$8
SPARSE=$9
PGZIP=${10}
TO_PGZIP=${11}
THROTTLE_BLOCK_SIZE=${12}

SPARSE_IT="";
if [ "$SPARSE" -eq "1" ]; then
	SPARSE_IT=" conv=sparse "
fi

# Lets start the DD -> GZIP -> Throttle -> UNZIP

if [ "$DISABLE_GZIP" -eq "1" ]; then
	
	ln -s $LOGFILE $ACTUAL_TRANSFER_LOG
	
	dd if=$SOURCE_DISK_PATH bs=24M | throttle -v -s $THROTTLE_BLOCK_SIZE -w 2 -M $SPEED 2>>$LOGFILE | ssh -oStrictHostKeyChecking=no -i /var/virtualizor/ssh-keys/id_rsa -q -p $TO_SSH_PORT root@$TO_IP dd $SPARSE_IT of=$DEST_DISK_PATH bs=24M 2>>$LOGFILE
	
else
	
	dd if=$SOURCE_DISK_PATH bs=24M | throttle -v -s $THROTTLE_BLOCK_SIZE -w 2 -M $SPEED 2>>$ACTUAL_TRANSFER_LOG | $PGZIP -1 | throttle -v -s $THROTTLE_BLOCK_SIZE -w 2 -M $SPEED 2>>$LOGFILE | ssh -oStrictHostKeyChecking=no -i /var/virtualizor/ssh-keys/id_rsa -q -p $TO_SSH_PORT root@$TO_IP "$TO_PGZIP -d | dd $SPARSE_IT of=$DEST_DISK_PATH bs=24M" 2>>$LOGFILE
	
fi

PIPESTATUS2=${PIPESTATUS[@]};
echo "$PIPESTATUS2" >>$LOGFILE

RET=0;

for i in $PIPESTATUS2; do
	RET=$(expr $RET + $i);
done;
echo $RET >>$LOGFILE;
echo "mig_completed" >>$LOGFILE

