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

BOOTSTRAP_FILE="/etc/init.d/calvados_bootstrap.cfg"
source $BOOTSTRAP_FILE
CGROUP_LOG_FILE="/var/log/cgroup"

# Check $VMTYPE and $VIRT_METHOD; 
# if in xr-vm and VIRT_METHOD is vm or
# if in host-os and VIR_METHOD is lxc; execute this script
# else exit
 
VMTYPE=`cat /proc/cmdline | sed 's/^.*vmtype=//' | cut -d" " -f1`
 
if [[ (("$VIRT_METHOD" == "lxc" && "$VMTYPE" == "hostos") || 
      ("$VIRT_METHOD" == "vm" && "$VMTYPE" == "xr-vm")) ]]; then
    echo `date` "$0 : Virt method $VIRT_METHOD, VM type $VMTYPE - Creating Cgroups" > $CGROUP_LOG_FILE
else
    echo `date` "$0 : Virt method $VIRT_METHOD, VM type $VMTYPE - Need not create Cgroups" > $CGROUP_LOG_FILE
    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
