werty1st
12/4/2013 - 7:36 PM

vbox autostart

vbox autostart

#!/bin/bash
#
#This init script autostarts necessary vms at boot 
#and saves running vms on shutdown

# Sed explanation: sed -e 's/^.//' -e 's/.$//'
#   1.  -e means to allow multiple arguments in a single sed command
#   2.  's/^.//' means to substitute (s) / at the beginning of the line (^), any character (.) / [substitute with nothing] /
#   3.  's/.$//' means to substitute (s) / any character (.), at the end of the line / [substitute with nothing] /

VBOXUSER=vbox
RUNNINGVMS=$(sudo -H -u $VBOXUSER vboxmanage list runningvms | cut -d " " -f1 | sed -e 's/^.//' -e 's/.$//')
STOPPEDVMS=$(sudo -H -u $VBOXUSER vboxmanage list vms | cut -d " " -f1 | sed -e 's/^.//' -e 's/.$//')

case "$1" in
  start)
        for i in $STOPPEDVMS
                do
                        echo "Starting" $i "VM"
                        sudo -H -u $VBOXUSER vboxmanage startvm $i --type headless
                        sleep 5
                done
    ;;
  stop)
        for i in $RUNNINGVMS
                do
                        echo "Saving state of" $i "VM"
                        sudo -H -u  $VBOXUSER vboxmanage controlvm $i savestate
                done
    ;;
  *)
    echo "Usage: /etc/init.d/startvm {start|stop}"
    exit 1
    ;;
esac

exit 0