#!/bin/bash

ID="$2"
PRINT=y

export LANG=en_US.UTF-8

. /unas/sbin/vmdashboard/log

log() {
    log_vm "$USER" clone "$ID" "domain" "$DOMAIN" "$UUID" "$@"
    if [ "$PRINT" == "y" ];then
        echo "$@"
    fi
}

skippassthrough() {
    IFS_BAK="$IFS"
    IFS=$(echo -en "\n\b")
    for blk in `virsh domblklist --details "$DOMAIN" | tail -n +3 | head -n -1`;do
        if echo "$blk" | grep -Eq '^\sfile\s+disk\s+';then
            disk=`echo "$blk" | grep -Po '\sfile\s+disk\s+\S+\s+\K(.*)'`
            if [ `file --dereference --mime-type --brief "$disk"` == "inode/blockdevice" ];then
                echo -n " --skip-copy "`echo "$blk" | awk '{print $3}'`
            fi
        fi
    done
    IFS="$IFS_BAK"
}

updatexml() {
    EDITOR="xmlstarlet edit -L -N unas=\"http://www.u-nas.cn/vm/xmlns\" -u \"//domain//metadata//unas:pool\" -v \"$POOL\" " virsh edit --domain "$TARGET"
    IFS_BAK="$IFS"
    IFS=$(echo -en "\n\b")
    for blk in `virsh domblklist --details "$TARGET" | tail -n +3 | head -n -1`;do
        if echo "$blk" | grep -Eq '^\sfile\s+disk\s+';then
            disk=`echo "$blk" | grep -Po '\sfile\s+disk\s+\S+\s+\K(.*)'`
            if [ `file --dereference --mime-type --brief "$disk"` != "inode/blockdevice" ];then
                new_name="$POOLPATH/"$(basename "$disk")
                mv "$disk" "$new_name"
                EDITOR="/bin/sed -i \"s#$disk#$new_name#g\"" virsh edit --domain "$TARGET"
                # We do not know the pool name of the original vol.
                # We can only guess one
                virsh pool-refresh --pool "$(basename $(dirname \"$disk\"))"
            fi
        fi
    done
    IFS="$IFS_BAK"
    virsh pool-refresh --pool "$POOL"
}

clone() {
    log INFO Start to "$TARGET"
    if virt-clone --original "$DOMAIN" --auto-clone --name "$TARGET" `skippassthrough` --check all=off;then
        updatexml
        log INFO Succeed to "$TARGET"
    else
        log ERROR Failed to "$TARGET" `sed ':a;N;$!ba;s/\n/<br>/g;s/|/ /g' /run/vmdashboard/domain/clone/$ID/err.log`
    fi
}

case "$1" in
    start)
        clone
    ;;

    clean)
        log DEBUG Clear tmp file
        rm -rf /run/vmdashboard/domain/clone/$ID
    ;;

    *)
        echo "clone called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

exit 0
