#!/bin/sh
# copyright (C) 2013-2014 FUJITSU LIMITED All Rights Reserved

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

# check root
if [ ${EUID:-${UID}} != 0 ]; then
    echo "error: Because you are not root, you cannot execute this command. "
    exit 1
fi

# cgroups path
CPUSET_LXCFMAINTENANCE="/sys/fs/cgroup/cpuset/lxcf-maintenance.slice"
CPU_LXCFMAINTENANCE="/sys/fs/cgroup/cpu/lxcf-maintenance.slice"
MEM_LXCFMAINTENANCE="/sys/fs/cgroup/memory/lxcf-maintenance.slice"

# check options
while getopts c:m:i:h OPT
do
  case $OPT in
    "c" )
	# set CPU
	echo -n 100000 > ${CPU_LXCFMAINTENANCE}/cpu.cfs_period_us;
	echo -n  `expr $OPTARG \* 1000` > ${CPU_LXCFMAINTENANCE}/cpu.cfs_quota_us;
    ;;
    "m" )
	#set MEMORY
	echo -n `expr $OPTARG \* 1024 \* 1024` > ${MEM_LXCFMAINTENANCE}/memory.limit_in_bytes;
    ;;
    "i" )
	#set CPU number
	echo -n  $OPTARG  > ${CPUSET_LXCFMAINTENANCE}/cpuset.cpus;
    ;;
    "h" )
	# display usage
	echo "usage: lxcf maintenance [-h] [ -c cpu(%) ] [-m MEMORY(M) ] [ -i CPU_Number ] COMMAND"
    ;;
  esac
done

shift `expr $OPTIND - 1`

# set pid to cgroups
echo $$ > ${CPU_LXCFMAINTENANCE}/tasks
echo $$ > ${MEM_LXCFMAINTENANCE}/tasks

# display resource
CPUP=`cat ${CPU_LXCFMAINTENANCE}/cpu.cfs_quota_us`
CPUN=`cat ${CPUSET_LXCFMAINTENANCE}/cpuset.cpus`
MEMORYLIMIT=`cat ${MEM_LXCFMAINTENANCE}/memory.limit_in_bytes`
echo "Resource allocated in lxcf-maintenance.slice"
echo "CPU :" `expr ${CPUP} \/ 1000` "%";
echo "CPU NO.:" ${CPUN}
echo "MEMORY :" `expr ${MEMORYLIMIT} \/ 1024 \/ 1024` "MB";
echo

# exec command
if [ $# -eq 0 ] ; then
	PS1="lxcf-maintenance # " /bin/bash
else
	. $*
fi

exit $?
