scripts/vm.zsh

63 lines
1.0 KiB
Bash
Executable File

#!/bin/zsh
autoload colors
colors
if [ "$#" -lt 2 ]; then
echo "Usage: $0 {boot,halt,reboot,restart,shutdown,start,stop} {libvirt VM, ...}"
exit 1
fi
function vm_boot() {
if virsh start $1 1>/dev/null 2>/dev/null; then
echo "$fg_bold[green]Starting VM: $fg_bold[white]$1$reset_color"
until nc -z -w 5 $1 22 2>/dev/null; do
sleep 5
done
fi
}
function vm_shutdown() {
if virsh shutdown $1 1>/dev/null 2>/dev/null; then
echo "$fg_bold[red]Stopping VM: $fg_bold[white]$1$reset_color"
while nc -z -w 5 $1 22 2>/dev/null; do
sleep 5
done
while virsh list --name | grep ^$1$ >/dev/null; do
sleep 5
done
fi
}
function vm_reboot() {
vm_shutdown $1
vm_boot $1
}
TRAPEXIT() {
if [[ ! -z "$(jobs -pr)" ]]; then
for job in ($(jobs -pr)); do
kill -9 $job
done
fi
}
for vm in "${@:2}"; do
case $1 in
"boot" | "start")
vm_boot $vm &
;;
"shutdown" | "stop" | "halt")
vm_shutdown $vm &
;;
"reboot"|"restart")
vm_reboot $vm &
;;
*)
echo "Boot, reboot, or shudown?"
exit 1
;;
esac
done
wait $(jobs -pr)