1#!/bin/sh
2
3# PROVIDE: vboxinit
4# REQUIRE: LOGIN vboxnet vboxwebsrv sshd
5# KEYWORD: shutdown
6#
7# Add the following line to /etc/rc.conf[.local] to enable vboxinit
8#
9# vboxinit_enable (bool):	Set to "NO" by default.
10#				Set it to "YES" to enable vboxinit.
11#				stop and faststop are always enabled.
12# vboxinit_user (str):		Default user account to run with.
13# 				(default: %%VBOXUSER%%)
14# vboxinit_home (str):		Default home directory to run with.
15#				(default: home of user ${vboxinit_user}
16# vboxinit_stop (str):		Default stop cmd for VBoxManage controlvm.
17#				(default: savestate)
18# vboxinit_start_delay (int):	Default startup delay in seconds.
19#				(default: 0)
20# vboxinit_stop_delay (int):	Default shutdown delay in seconds.
21#				(default: 0)
22#
23# Set the "Startup Mode" to "Automatic" for the virtual machine in
24# phpvirtualbox to automatically start the virtual machine during OS boot.
25#
26
27. /etc/rc.subr
28
29name="vboxinit"
30rcvar="${name}_enable"
31
32start_cmd="${name}_start"
33stop_cmd="${name}_stop"
34status_cmd="${name}_status"
35restart_cmd="${name}_restart"
36
37vboxinit_start()
38{
39	# Get a list of all machines with autorun enabled in phpvirtualbox
40	${su_command} "${command} list vms | /usr/bin/tr -d '{}\"'" | while read VMNAME UUID; do
41		STARTUP=$(${su_command} "${command} getextradata ${UUID} 'pvbx/startupMode'" | /usr/bin/cut -d' ' -f2)
42		if [ "${STARTUP}" == "auto" ]; then
43			echo "${name}: starting machine ${VMNAME} ..."
44			${su_command} "${command} startvm ${UUID} --type headless"
45			sleep "${vboxinit_start_delay}"
46		fi
47	done
48}
49
50vboxinit_stop()
51{
52	# Get all running machines
53	${su_command} "${command} list runningvms | /usr/bin/tr -d '{}\"'" | while read VMNAME UUID; do
54		echo "${name}: stopping machine ${VMNAME} with action '${vboxinit_stop}' ..."
55		${su_command} "${command} controlvm ${UUID} ${vboxinit_stop}"
56		sleep "${vboxinit_stop_delay}"
57	done
58}
59
60vboxinit_status()
61{
62	# List all running machines
63	${su_command} "${command} list runningvms"
64}
65
66vboxinit_restart()
67{
68	vboxinit_stop
69	vboxinit_start
70}
71
72load_rc_config $name
73
74: ${vboxinit_enable="NO"}
75: ${vboxinit_user="%%VBOXUSER%%"}
76: ${vboxinit_home=$(/usr/sbin/pw usershow -7 -n "${vboxinit_user}" | /usr/bin/cut -d: -f6)}
77: ${vboxinit_stop="savestate"}
78: ${vboxinit_start_delay="0"}
79: ${vboxinit_stop_delay="0"}
80HOME=${vboxinit_home}
81USER=${vboxinit_user}
82export HOME USER
83
84command="%%VBOXDIR%%/VBoxManage"
85su_command="/usr/bin/su -m ${vboxinit_user} -c"
86
87if [ "x$1" = "xstop" ] || [ "x$1" = "xfaststop" ]; then
88	vboxinit_enable="YES"
89fi
90
91run_rc_command "$1"
92