#!/bin/sh
#
# lxc Start/Stop LXC autoboot containers
#
# chkconfig: 345 99 01
# description: Starts/Stops all LXC containers configured for autostart.
#
### BEGIN INIT INFO
# Provides: lxc
# Default-Start: 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Bring up/down LXC autostart containers
# Description: Bring up/down LXC autostart containers
### END INIT INFO

# Source function library.
. /etc/init.d/functions

# Check for needed utility program
[ -x /usr/bin/lxc-autostart ] || exit 1

# If libvirtd is providing the bridge, it might not be
# immediately available, so wait a bit for it before starting
# up the containers or else any that use the bridge will fail
# to start
wait_for_bridge()
{
    [ -f /etc/lxc/default.conf ] || { return 0; }

    BRNAME=`grep '^[ 	]*lxc.network.link' /etc/lxc/default.conf | sed 's/^.*=[ 	]*//'`
    if [ -z "$BRNAME" ]; then
	return 0
    fi

    for try in `seq 1 30`; do
	ifconfig -a |grep "^$BRNAME" >/dev/null 2>&1
	if [ $? = 0 ]; then
	    return
	fi
	sleep 1
    done
}

# See how we were called.
case "$1" in
  start)
	[ ! -f /var/lock/subsys/lxc ] || { exit 0; }

	# Start containers
	wait_for_bridge
	action $"Starting LXC containers: " /usr/bin/lxc-autostart
	touch /var/lock/subsys/lxc
	;;
  stop)
	action $"Stopping LXC containers: " /usr/bin/lxc-autostart -s
	rm -f /var/lock/subsys/lxc
	;;
  restart|reload|force-reload)
	$0 stop
	$0 start
	;;
  *)
	echo $"Usage: $0 {start|stop|restart|reload|force-reload}"
	exit 2
esac
exit $?
