#!/bin/bash

# Copyright (C) 2016 NIWA Hideyuki

FULCONDRIVER=`fulcon driver-name`
PATH=/usr/lib/fulcon/driver/$FULCONDRIVER:/usr/lib/fulcon/lib:$PATH

SLOTOSDIR=/var/lib/slot-os

usage()
{
	echo "usage: sysgen NUMBER"
}

lsdir() {
  ls -f --ind=none $1 | sed '/^\.\{1,2\}$/d'
}

ARGN=$#
if [ $ARGN -ne 1 -a $ARGN -ne 2 ]; then
	usage
	exit -1
fi

if [ $ARGN -eq 1 -a x"$1" == x"sysgen" ]; then
	usage
	exit -1
fi

NUM=$1

if [ $ARGN -eq 1 ]; then
	IMAGE=fulcon/slot-os
else
	IMAGE=$2
fi

NUM=`echo $NUM | sed -e 's/slot//'` 
NUM=`expr $NUM + 0`
NAME=`printf "slot%02d" $NUM`

# check image
RCK=0
if [ `slot-os backup-list | wc -l` -eq 0 ]; then
	echo "error: The image which can be carried out isn't found."
	exit -1
fi	
for i in `slot-os backup-list`
do
	if [ x"fulcon/$i" == x"$IMAGE" ]; then
		RCK=1
		break
	fi
done
if [ $RCK -eq 0 ]; then
	echo "error: $IMAGE is not found"
	exit -1
fi

# check slot number
if [ ! -x $SLOTOSDIR/slot/$NUM ]; then
	printf "error: slot%02s is not exist" $NUM
	exit -1
fi

# container is generated
fulcon sysgen -c $IMAGE $NAME
if [ $? -ne 0 ] ; then
	echo "error: $NAME is not able to start"
	exit -1
fi

# make a slot
echo $NAME > $SLOTOSDIR/slot/$NUM/fulcon

fulcon resource  \
	-c `cat $SLOTOSDIR/slot/$NUM/cpu` \
	-n `cat $SLOTOSDIR/slot/$NUM/cpuset` \
	-m `cat $SLOTOSDIR/slot/$NUM/memory` \
	$NAME >& /dev/null

# start network
OLDPATH=$PATH
PATH=/usr/lib/fulcon/sbin:$PATH
mkdir -p $SLOTOSDIR/slot/$NUM/net
for i in `lsdir $SLOTOSDIR/slot/$NUM/net`
do
	NEWFILE=`echo $i | sed -e "s/$OLDNAME/$NAME/"`
	mv $SLOTOSDIR/slot/$NUM/net/$i $SLOTOSDIR/slot/$NUM/net/$NEWFILE >& /dev/null
	bash $SLOTOSDIR/slot/$NUM/net/$NEWFILE $NAME
done

PATH=$OLDPATH

