#!/bin/sh -e
#
# Copyright (C) 2007,2008 Canonical, Ltd.
# Author: Jamie Strandboge <jamie@canonical.com>
# License: GPLv3
#
# Simple update script
#

ustconf="$HOME/.uqt-vm-tools.conf"
if [ -s "$ustconf" ]; then
    . "$ustconf"
else
    echo "Could not find '$ustconf'"
    exit 1
fi

. $UQT_VM_TOOLS/libvm.sh
abort_if_root

help() {
    echo "Usage: vm-modify '<old sed expr>' '<new sed expr>' <vm1> <vm2>"
    echo ""
    echo "Eg:"
    echo "$ vm-modify '<currentMemory>262144</currentMemory>' '<currentMemory>393216</currentMemory>' sec-hardy-amd64"
}

force=""
if [ "$1" = "-f" ]; then
    force="yes"
    shift || true
fi

if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then
    help
    exit 1
fi
old="$1"
new="$2"
shift 2

tmpdir=`mktemp -d`
trap "rm -rf $tmpdir" EXIT HUP INT QUIT TERM

for i in "$@" ; do
    if ! vm_exists $i ; then
        echo "'$i' does not exist"
        continue
    fi

    if vm_running $i ; then
        echo "'$i' is running, skipping"
        continue
    fi

    xml="${tmpdir}/${i}.xml"
    virsh --connect ${vm_connect} dumpxml $i > "$xml"

    sed -i "s#$old#$new#" "$xml"

    ans="y"
    if [ "$force" != "yes" ]; then
        cat "$xml"
        echo ""
        echo -n "Is this correct (y|N)? "
        read ans
    fi
    if [ "$ans" = "y" ] || [ "$ans" = "Y" ]; then
        virsh --connect ${vm_connect} define "$xml"
    else
        echo "Not applying changes to '$i'"
    fi
done

exit 0
