#!/bin/bash
#
# LXC setup script
#
# This script does the basic initialization of LXC infra
# Copyright (c) 2014-2015 by Cisco Systems, Inc.
# All rights reserved.

BOOTSTRAP_FILE="/etc/init.d/calvados_bootstrap.cfg"
source $BOOTSTRAP_FILE

# This script would be executed only if VIRT_METHOD=lxc
if [[ $VIRT_METHOD != "lxc" ]]; then
    exit 0
fi

vmtype=`cat /proc/cmdline | sed 's/^.*vmtype=//' | cut -d" " -f1`
if [[ "$vmtype" != "hostos" ]]; then
    exit 0
fi

set -m
declare -a cgroup_dirlist=('devices' 'memory' 'cpuacct' 'cpuset' 'cpu' 'freezer')
prog="cgroup-init"

function create_cgroup_dir(){
    for d in "${cgroup_dirlist[@]}"
    do
        mkdir -p /dev/cgroup/$d
    done
}
readonly -f create_cgroup_dir

function mount_cgroup(){

    for d in "${cgroup_dirlist[@]}"
    do
        if [ -e /dev/cgroup/$d ]
        then
            mount -t cgroup cgroup -o $d /dev/cgroup/$d
        fi
    done
}
readonly -f mount_cgroup

start()
{
    echo "Starting $prog"
    # Create and mount necessary cgroups for LXC initialization
    create_cgroup_dir
    mount_cgroup
}

stop()
{
    echo "Stoping $prog"
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart}"
        RETVAL=1
esac
exit $RETVAL
