1#!/bin/sh -e
2
3# State Key
4# NOSTATE: 0 - no state
5# RUNNING: 1 - the domain is running
6# BLOCKED: 2 - the domain is blocked on resource
7# PAUSED: 3 - the domain is paused by user
8# SHUTDOWN: 4 - the domain is being shut down
9# SHUTOFF: 5 - the domain is shut off
10# CRASHED: 6 - the domain is crashed
11# PMSUSPENDED: 7 - the domain is suspended by guest power management
12# LAST: 8 NB: this enum value will increase over time as new events are added to the libvirt API. It reflects the last state supported by this version of the libvirt API.
13
14vmname="$1"
15
16[ "$vmname" = '' ] && printf 'you must set $vmname\n' && exit 1
17
18if printf "$vmname" | grep -vqE '^(cvm|capsul)-[a-z0-9]{10}$'; then
19 printf 'vmname %s must match ^capsul-[a-z0-9]{10}$\n' "$vmname"
20 exit 1
21fi
22
23state="$(virsh domstats $vmname | grep state.state | cut -d '=' -f 2)"
24
25[ "$state" = '' ] && printf 'state was not detected. must match ^[0-8]$\n' && exit 1
26
27if printf "$state" | grep -vqE '^[0-8]$'; then
28 printf 'state %s must match ^[0-8]$\n' "$state"
29 exit 1
30fi
31
32case "$state" in
33 [1-47]) virsh shutdown --mode acpi "$vmname" > /dev/null ;;
34 [5-6]) printf "%s is already off\n" "$vmname" ;;
35esac
36