summaryrefslogtreecommitdiffstats
path: root/vboxinit
blob: a3ecb3e9af9df1a439c808e1ece8b9a7d30d62c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/bin/sh

# $FreeBSD: www/phpvirtualbox/files/vboxinit.in $
#
# PROVIDE: vboxinit
# REQUIRE: LOGIN FILESYSTEMS vboxnet sshd
# KEYWORD: shutdown
#
# Add the following line to /etc/rc.conf[.local] to enable vboxinit
#
# vboxinit_enable (bool):	Set to "NO" by default.
#				Set it to "YES" to enable vboxinit.
# vboxinit_user (str):		Default user account to run with.
# 				(default: vboxusers)
# vboxinit_home (str):		Default home directory to run with.
#				(default: home of user ${vboxinit_user}
# vboxinit_stop (str):		Default stop cmd for VBoxManage controlvm.
#				(default: savestate)
# vboxinit_start_delay (int):	Default startup delay in seconds.
#				(default: 0)
# vboxinit_stop_delay (int):	Default shutdown delay in seconds.
#				(default: 0)

. /etc/rc.subr

name="vboxinit"
rcvar=vboxinit_enable

start_cmd="${name}_start"
stop_cmd="${name}_stop"
status_cmd="${name}_status"
restart_cmd="${name}_restart"

vm_name()
{
	local UUID=$1
	${su_command} "${command} showvminfo ${UUID} | /usr/bin/grep -m 1 '^Name:' | /usr/bin/sed 's/^Name:[ \t]*//'"
}

vboxinit_start()
{
	# Get all autostart machines
	MACHINES=$(${su_command} "${command} list vms | /usr/bin/awk '{ print \$NF }' | /usr/bin/sed -e 's/[{}]//g'")
	for UUID in ${MACHINES}; do
		STARTUP=$(${su_command} "${command} getextradata ${UUID} 'pvbx/startupMode'" | /usr/bin/awk '{ print $NF }')
		if [ "${STARTUP}" == "auto" ]; then
			VMNAME=$(vm_name ${UUID})
			echo "${name}: starting machine ${VMNAME} ..."
			${su_command} "${command} startvm ${UUID} --type headless"
			sleep ${vboxinit_start_delay}
		fi
	done
}

vboxinit_stop()
{
	# Get all started machines
	MACHINES=$(${su_command} "${command} list runningvms | /usr/bin/awk '{ print \$NF }' | /usr/bin/sed -e 's/[{}]//g'")
	for UUID in ${MACHINES}; do
		VMNAME=$(vm_name ${UUID})
		echo "${name}: saving machine ${VMNAME} state ..."
		${su_command} "${command} controlvm ${UUID} savestate"
		sleep ${vboxinit_stop_delay}
	done
}

vboxinit_status()
{
	${su_command} "${command} list runningvms"
}

vboxinit_restart()
{
	vboxinit_stop
	vboxinit_start
}

load_rc_config $name

: ${vboxinit_enable="NO"}
: ${vboxinit_user="vboxusers"}
: ${vboxinit_home=$(/usr/sbin/pw usershow -7 -n "${vboxinit_user}" | /usr/bin/cut -d: -f6)}
: ${vboxinit_stop="savestate"}
: ${vboxinit_start_delay="0"}
: ${vboxinit_stop_delay="0"}
HOME=${vboxinit_home}
USER=${vboxinit_user}

command="/usr/local/bin/VBoxManage"
su_command="/usr/bin/su -m ${vboxinit_user} -c"

run_rc_command "$1"