#!/bin/bash

# Copyright (C) 2015-2016 NIWA Hideyuki

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

SLOTOSDIR=/var/lib/slot-os


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

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

if [ $# -ne 1 ]; then
	usage
	exit -1
fi

# check args
NUM=$1
expr $NUM - 1 >& /dev/null
if [ $? -ge 2 ]; then
	usage
	exit -1
fi
NUMSAVE=$NUM
NUM=`expr $NUM - 1`
if [ $NUM -lt -1 ]; then
	usage
	exit -1
fi

CPUNUM=`cat /sys/fs/cgroup/cpuset/cpuset.cpus | awk -F - '{print $NF}' | awk -F , '{print $NF}'`
CPUNUM=`expr $CPUNUM + 1`

mkdir -p $SLOTOSDIR/slot
for i in `seq 0 $NUM`
do
	mkdir -p $SLOTOSDIR/slot/$i
	if [ ! -f $SLOTOSDIR/slot/$i/fulcon ]; then
		echo '-' > $SLOTOSDIR/slot/$i/fulcon
		cat /sys/fs/cgroup/cpuset/cpuset.cpus > $SLOTOSDIR/slot/$i/cpuset
		echo 512m > $SLOTOSDIR/slot/$i/memory
	fi
	CPUPER=`expr $CPUNUM '*' 100 / $NUMSAVE`
	if [ $CPUPER -gt 100 ]; then
		CPUPER=100
	fi
	echo $CPUPER > $SLOTOSDIR/slot/$i/cpu
done

cd  $SLOTOSDIR/slot/
for i in `ls -1 | sort -n`
do
	if [ ! $i -le $NUM ]; then
		slot-erase $i 
		rm -rf $SLOTOSDIR/slot/$i
	fi
done

for i in `seq 0 $NUM`
do
	SLOTNAME=`printf "slot%02d" $i`
	if [ x"`cat $SLOTOSDIR/slot/$i/fulcon`" == x"-" ]; then
		echo -n "create "
		slot-sysgen $SLOTNAME
	else
		echo initialized $SLOTNAME
		slot-sysgen $SLOTNAME >& /dev/null
	fi
done

exit 0
