#!/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

# check options
VAL_PATH=""
FLG_P=0
FILEPATH=""

while getopts sjc:p: OPT
do
  case $OPT in
    "p" ) FLG_P=1 ; VAL_PATH="-p" ;   FILEPATH=$OPTARG ;;
  esac
done

shift `expr $OPTIND - 1`

if [ $# -ne 3  -a  $# -ne 4 ] ; then
  echo "usage : clone-n [ -p path ] SRCNAME NAME NUM"
  echo "        clone-n [ -p path ] SRCNAME NAME NUM1 NUM2"
  exit -1
fi

MAXNUM=50
SRCNAME=$1
LNAME=$2

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

  NUM2=$4
  if ! expr "$NUM2" : '[0-9]*' > /dev/null ; then
    echo "illegal number :" $NUM2
    exit -1
  fi
else
  NUM1=1
  NUM2=$3
  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

for i in `seq $NUM1 $NUM2`
do
  /usr/lib64/lxcf/lxcf-clone ${VAL_PATH} ${FILEPATH} ${SRCNAME} ${LNAME}`printf "%04d" ${i}` 
done

exit 0

