#!/bin/bash

# Copyright (C) 2016 NIWA Hideyuki

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

FULCONDIR=/var/lib/fulcon
SLOTOSDIR=/var/lib/slot-os

usage()
{
	echo "usage: list [ -c ] [ SLOT_NUMBER ...]"
}

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

# check options
FLG_C=0

while getopts c OPT
do
  case $OPT in
  "c" ) FLG_C=1 ;;
  \?  ) usage; exit -1;;
  esac
done
shift `expr $OPTIND - 1`

list1()
{
	i=$1
	CNAME=`printf "slot%02d" $i`
	STATUS=`fulcon-status $CNAME`
	if [ !  -f $FULCONDIR/container/$CNAME/imagename ]; then
		return
	fi
	IMAGE=`sed -e 's%fulcon/%%' $FULCONDIR/container/$CNAME/imagename`

	# network information
	IPADDR=""
	if [ x"$STATUS" == x"RUNNING" ]; then
		IPADDR=`fulcon-ip $CNAME`
	fi

	if [ -d $SLOTOSDIR/slot/$i/net ]; then
		for k in `lsdir $SLOTOSDIR/slot/$i/net`
		do
			IP1=`awk '{printf "%s ",$3}' $SLOTOSDIR/slot/$i/net/$k`
			IPADDR="$IPADDR $IP1"
		done
	fi

	# autostart information
	if [ -f $SLOTOSDIR/slot/$i/autostart ]; then
		AUTOSTART="A"
	else
		AUTOSTART="-"
	fi

	if [ -d $SLOTOSDIR/slot/$i ]; then
		printf "%2d : %-9s %s %3s%% %3s %s %1s %s " \
			$i $STATUS $CNAME \
			`cat $SLOTOSDIR/slot/$i/cpu` \
			`cat $SLOTOSDIR/slot/$i/cpuset` \
			`cat $SLOTOSDIR/slot/$i/memory` \
			$AUTOSTART \
			$IMAGE
	fi

	echo $IPADDR
}


display_list()
{
	for i in $NUMS
	do
		NUM=$i
		NUM=`echo $NUM | sed -e 's/slot//'` 
		NUM=`expr $NUM + 1`
		if [ $? -ne 0 ]; then
			echo "error: slot $i is not exist"
			continue
		else
			NUM=`expr $NUM - 1`
		fi

		if [ -d $SLOTOSDIR/slot/$NUM ]; then
			CNAME=`cat $SLOTOSDIR/slot/$NUM/fulcon`
			list1 $NUM
		else
			echo "error: slot $NUM is not exist"
		fi
	done
}

if [ ! -d $SLOTOSDIR/slot -o ! -d $SLOTOSDIR/slot/0 ]; then
	exit -1
fi

NUMS=$*

FLG=0
if [ $# -eq 0 -o x"$1" == x"list" ]; then
	NUMS=`lsdir $SLOTOSDIR/slot | sort -n`
	FLG=1
fi


if [ $FLG_C -eq 0 ]; then
	display_list
else
	tput clear

	while : 
	do
		if [ $FLG -eq 1 ]; then
			NUMS=`lsdir $SLOTOSDIR/slot | sort -n`
		fi

		display_list
		sleep 1
		tput clear
	done
fi

exit 0
