#!/bin/sh

### BEGIN INIT INFO
# Provides:             lxc-docker
# Required-Start:       $syslog $remote_fs
# Required-Stop:        $syslog $remote_fs
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    Linux container runtime
# Description:          Linux container runtime
### END INIT INFO

DOCKER=/usr/bin/lxc-docker

# Check lxc-docker is present
[ -x $DOCKER ] || (log_failure_msg "lxc-docker not present"; exit 1)

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin

# Get lsb functions
. /lib/lsb/init-functions

check_root_id ()
{
  if [ "$(id -u)" != "0" ]; then
    log_failure_msg "LXC Docker must be run as root"; exit 1
  fi
}

case "$1" in
  start)
    check_root_id || exit 1
    log_begin_msg "Starting LXC Docker"
    mount | grep cgroup >/dev/null || mount -t cgroup none /sys/fs/cgroup
    start-stop-daemon --start --background --exec "$DOCKER" -- -d
    log_end_msg $?
    ;;

  stop)
    check_root_id || exit 1
    log_begin_msg "Stopping LXC Docker"
    docker_pid=`pgrep -f "$DOCKER -d"`
    [ -n "$docker_pid" ] && kill $docker_pid
    log_end_msg $?
    ;;

  restart)
    check_root_id || exit 1
    docker_pid=`pgrep -f "$DOCKER -d"`
    [ -n "$docker_pid" ] && /etc/init.d/lxc-docker stop
    /etc/init.d/lxc-docker start
    ;;

  force-reload)
    check_root_id || exit 1
    /etc/init.d/lxc-docker restart
    ;;

  status)
    docker_pid=`pgrep -f "$DOCKER -d"`
    if [ -z "$docker_pid" ] ; then
      echo "lxc-docker not running"
    else
      echo "lxc-docker running (pid $docker_pid)"
    fi
    ;;

  *)
    echo "Usage: /etc/init.d/lxc-docker {start|stop|restart|status}"
    exit 1
    ;;
esac

exit 0