#!/bin/bash

# LXCF - LXC Facility
# Copyright (C) 2013-2014 FUJITSU LIMITED

# 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} -ne 0 ] ; then
  echo "error: Because you are not root, you cannot execute this command."
  exit 1
fi

# check default separate model
/usr/lib64/lxcf/lxcf-config
if [ -f /etc/lxcf/separate ] ; then
  FLG_S=1 ; VAL_SEPARATE="-s"
else
  FLG_S=0 ; VAL_SEPARATE="-j"
fi

# check options
FLG_C=0 ; VAL_CONFIG="" ; JSONFILE=""
FLG_P=0 ; VAL_PATH="" ; FILEPATH=""

while getopts sjc:p: OPT ; do
  case $OPT in
  s) FLG_S=1 ; VAL_SEPARATE="-s" ;;
  j) FLG_S=0 ; VAL_SEPARATE="-j" ;;
  c) FLG_C=1 ; VAL_CONFIG="-c" ; JSONFILE=$OPTARG ;;
  p) FLG_P=1 ; VAL_PATH="-p" ; FILEPATH=$OPTARG ;;
  esac
done
shift $((OPTIND - 1))

MAXNUM=50
LNAME=$1

if [ $# -eq 2 ] ; then
  NUM1=1 ; NUM2=$2
elif [ $# -eq 3 ] ; then
  NUM1=$2 ; NUM2=$3
else
  cat <<- EOF
	usage: ${0##/*} [-p path] [-c resourcefile] NAME NUM
	       ${0##/*} [-p path] [-c resourcefile] NAME NUM1 NUM2
	EOF
  exit 1
fi

if [[ ! "$NUM1" =~ ^[0-9]+$ ]] ; then
  echo "illegal number: $NUM1"
  exit 1
elif [[ ! "$NUM2" =~ ^[0-9]+$ ]] ; then
  echo "illegal number: $NUM2"
  exit 1
elif ! /usr/lib64/lxcf/lxcf-parmchk-num $NUM1 ; then
  echo "not integer: $NUM1"
  exit 1
elif ! /usr/lib64/lxcf/lxcf-parmchk-num $NUM2 ; then
  echo "not integer $NUM2"
  exit 1
elif [ $NUM1 -lt 1 -o $NUM1 -gt $MAXNUM ] ; then
  echo "illegal range: $NUM1"
  exit 1
elif [ $NUM2 -le $NUM1 -o $NUM2 -gt $MAXNUM ] ; then
  echo "illegal range: $NUM2"
  exit 1
fi

for i in `seq -f "%04g" $NUM1 $NUM2` ; do
  /usr/lib64/lxcf/lxcf-sysgen $VAL_SEPARATE $VAL_CONFIG $JSONFILE \
      $VAL_PATH $FILEPATH $LNAME$i
done

exit 0
