#!/bin/sh

show_help() {
  c="  `basename $0`"
  echo "Usage:"
  echo "$c --help				# this help"
  echo "$c --restart name			# restart"
  echo "$c --shutdown name			# shutdown and sync"
  echo "$c --start name				# sync and start"
  echo "$c --rename name newname		# rename guest"
  echo "$c --migrate name host [--live]	# live migrate to host"
  echo "$c --move name host [newname]	# offline move guest"
  exit 0
}

shutdown_and_restart() {
  set -x
  virsh shutdown $1
  virsh console $1

  sleep 1s
  sync
  echo 3 > /proc/sys/vm/drop_caches
  sync

  if [ "$2" = "restart" ]; then
    sleep 3s
    virsh start $1 --console
    exit 0
  fi

  sleep 5s
  sync
  echo 3 > /proc/sys/vm/drop_caches
}

start_guest() {
  set -x
  sync
  echo 3 > /proc/sys/vm/drop_caches
  sync
  sleep 1s
  
  virsh start $1 --console
}

rename_guest() {
  TMP=`mktemp`
  virsh dumpxml $1 > $TMP
  sed -i "s|<name>$1</name>|<name>$2</name>|" $TMP
  virsh undefine $1
  virsh define $TMP
  rm -f $TMP
}

move_guest() {
  virsh shutdown $1
  virsh console $1
  echo 3 > /proc/sys/vm/drop_caches
  sync
  if [ "$3" ]; then
    M="$3"
  else
    M="$1"
  fi
  ssh root@$2 virsh start $M --console
}

if [ -z "$2" ]; then
  show_help
elif [ "$1" = "--restart" -o "$1" = "--reboot" ]; then
  shutdown_and_restart $2 restart
elif [ "$1" = "--shutdown" ]; then
  shutdown_and_restart $2
elif [ "$1" = "--start" ]; then
  start_guest $2
elif [ "$1" = "--rename" ]; then
  rename_guest "$@"
elif [ "$1" = "--move" ]; then
  move_guest "$@"  
elif [ "$1" = "--migrate" ]; then
  virsh migrate $4 $2 qemu+ssh://root@$3/system
else
  show_help
fi
