#!/bin/sh
# copyright (C) 2013 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


FLG_C=0
PARM_C=""
FLG_N=0
PARM_N=""
FLG_I=0
PARM_I=""
FLG_M=0
PARM_M=""
FLG_S=0
PARM_S=""

# check options
while getopts c:i:n:m:s: OPT
do
  case $OPT in
    "c" ) FLG_C=1; PARM_C="-c"; CPURATE=$OPTARG  ;;
    "i" ) FLG_I=1; PARM_I="-i"; CPUN=$OPTARG  ;;
    "n" ) FLG_N=1; PARM_N="-n"; NUMA=$OPTARG  ;;
    "m" ) FLG_M=1; PARM_M="-m"; MEMLIMIT=$OPTARG  ;;
    "s" ) FLG_S=1; PARM_S="-s"; MEMSWLIMIT=$OPTARG  ;;
  esac
done

shift `expr $OPTIND - 1`

if [ $# -ne 2  -a  $# -ne 3 ] ; then
  echo "usage : set-n [ -c CPURATE ] [ -i CPUN ] [ -n NUMA ] [ -m MEMLIMIT ] [ -s MEMSWLIMIT ] NAME NUM"
  echo "        set-n [ -c CPURATE ] [ -i CPUN ] [ -n NUMA ] [ -m MEMLIMIT ] [ -s MEMSWLIMIT ] NAME NUM1 NUM2"
  exit -1
fi

MAXNUM=50
LNAME=$1

if [ $# -eq 3 ] ; then
  NUM1=$2
  if ! expr "$NUM1" : '[0-9]*' > /dev/null ; then
    echo "illegal number :" $NUM1
    exit -1
  fi

  NUM2=$3
  if ! expr "$NUM2" : '[0-9]*' > /dev/null ; then
    echo "illegal number :" $NUM2
    exit -1
  fi
else
  NUM1=1
  NUM2=$2
  if ! expr "$NUM2" : '[0-9]*' > /dev/null ; then
    echo "illegal number :" $NUM2
    exit -1
  fi
fi

if ! /usr/lib64/lxcf/lxcf-parmchk-num $NUM1 ; then
  echo $NUM1 "is not a integer"
  exit 1
fi

if ! /usr/lib64/lxcf/lxcf-parmchk-num $NUM2 ; then
  echo $NUM2 "is not a integer"
  exit 1
fi

if [ $NUM1 -le 0 -o $NUM1 -gt $MAXNUM ]; then
  echo "illegal range :" $NUM1
  exit -1
fi

if [ $NUM1 -ge $NUM2 -o $NUM2 -le 0 -o $NUM2 -gt $MAXNUM ]; then
  echo "illegal range :" $NUM2
  exit -1
fi

# set parameter variable
parmvar=`echo "${PARM_C} ${CPURATE} ${PARM_I} ${CPUN} ${PARM_N} ${NUMA} ${PARM_M} ${MEMLIMIT} ${PARM_S} ${MEMSWLIMIT}"`

for i in `seq $NUM1 $NUM2`
do
  /usr/lib64/lxcf/sbin/set ${parmvar} ${LNAME}`printf "%04d" ${i}`
done

exit 0

