#!/bin/sh
#
# Copyright (C) 2009 Canonical, Ltd.
# Author: Jamie Strandboge <jamie@canonical.com>
# License: GPLv3
#
# Changes network for libvirt's default network. Useful when running libvirt
# within a virtual machine.
#

set -e

help() {
    echo "USAGE:"
    echo "  update_virtnet <orig> <new>"
    echo "Eg:"
    echo "$ update_virtnet 192.168.122 192.168.123"
}

tmp=`mktemp`
trap "rm -f $tmp" EXIT HUP INT QUIT TERM

connect="qemu:///system"
while getopts "c:h" opt
do
    case "$opt" in
        c) connect="$connect";;
        h|?)
            help
            exit 1
            ;;
    esac
done
shift $(($OPTIND - 1))

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

group="libvirtd"
if ! id | grep -q "$group" ; then
    cat <<EOM
Must be a in the $group group. Please do:
$ sudo adduser $USER $group
$ sg $group
$ $0 -c $connect $orig $new

If you are running this in a virtual machine after performing the above, you
may need to restart your network interface.
EOM
    exit 1
fi

virsh --connect="$connect" net-dumpxml default | sed "s/$orig/$new/g" > "$tmp"
virsh --connect="$connect" net-define "$tmp"
virsh --connect="$connect" net-destroy default
virsh --connect="$connect" net-start default

