#!/bin/bash
# lxc containers starter script
# based on skeleton from Debian GNU/Linux
### BEGIN INIT INFO
# Provides:          lxc
# Required-Start:    $syslog $remote_fs
# Required-Stop:     $syslog $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Linux Containers
# Description:       Linux Containers
### END INIT INFO

NAME=lxc
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
DESC="LXC containers"

SCRIPTNAME="/etc/init.d/lxc"

. /lib/lsb/init-functions

if [ -f /etc/default/$NAME ] ; then
  . /etc/default/$NAME
fi

if [ "x$RUN" != "xyes" ] ; then
  log_success_msg "$NAME init script disabled; edit /etc/default/$NAME"
  exit 0
fi

shopt -s nullglob
case "$1" in
  start)
    log_daemon_msg "Starting $DESC"
    for name in $ROOT_DIR/*/forceboot
    do  name=${name%/forceboot}
        name=${name#$ROOT_DIR/}
        # Skip it if it doesn't have an RFC952 hostname (e.g. no fooserv.~1~'s)
        [[ $name =~ ^[[:alnum:]]([[:alnum:]-]{0,61}[[:alnum:]])?$ ]] || continue
        lxc-start -n $name -f $CONF_DIR/$name.conf -d
        log_progress_msg $name
    done
    log_end_msg 0
    ;;
  stop)
    log_daemon_msg "Stopping $DESC"
    pkill -INT lxc-start   # Sends a ctrl-alt-del to containers' upstarts.
    i=300                  # Begin a spinlock, capped at five minutes.
    while
        then=$now now=$(lxc-ls | sort)
        # Print the lines that have disappeared since the previous iteration.
        for name in $(comm -23 <(cat <<<"$then") <(cat <<<"$now"))
        do log_progress_msg $name
        done
        [[ -n "$now" ]] && ((i--))
    do sleep 1
    done

    if [[ -z "$now" ]]
    then log_end_msg 0
    else log_end_msg 1
        log_daemon_msg "Killing  $DESC"
        for name in $now
        do  lxc-stop -n $name
            log_progress_msg $name
        done
        log_end_msg 0
    fi
    ;;
  restart|force-reload)
        "$0" stop
        "$0" start
    ;;
  status)
    for name in $ROOT_DIR/*/forceboot
    do  name=${name%/forceboot}
        name=${name#$ROOT_DIR/}
        # Skip it if it doesn't have an RFC952 hostname (e.g. no fooserv.~1~'s)
        [[ $name =~ ^[[:alnum:]]([[:alnum:]-]{0,61}[[:alnum:]])?$ ]] || continue
        lxc-info -n $name
    done
    ;;
  *)
    log_success_msg "Usage: $SCRIPTNAME {start|stop|force-reload|restart|status}"
    exit 1
    ;;
esac

exit 0
