#!/bin/sh

# Copyright (C) 2015-2016 NIWA Hideyuki

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

usage() {
	echo "usage: console [ -n REPEAT_NUMBER ] NAME"
}

# check options
OPT_FLG=""
FLG_N=0;RNUM=0

while getopts n: OPT
do
  case $OPT in
    "n" ) FLG_N=1 ; RNUM=$OPTARG ;;
    \?  ) usage; exit -1;;
  esac
done

shift `expr $OPTIND - 1`

if [ $FLG_N -eq 1 ]; then
	if [ $# -ne 1 ]; then
		usage
		exit -1
	fi
	NAME=$1
	if [ $RNUM -gt 0 -a $RNUM -lt 1000 ]; then
		for i in `seq $RNUM`
		do
			N=`printf "%04d" $i`
			ST=`fulcon list | awk '{if ($1 == "'$NAME$N'") {if ($2 == "RUNNING"){print 0} else {print 1}}}'`
			if [ x"$ST" != x"0" ]; then
				echo $NAME$N "is not running"
			else	
				gnome-terminal -e "lib-console $OPT_FLG $NAME$N" >& /dev/null
				if [ $? -ne 0 ]; then
					echo "error: can't open new gnome-terminal:" $NAME$N
				fi
			fi
		done;
		exit 0
	else
		echo "error: REPEAT_NUMBER must be [1...999]"
		exit -1
	fi

fi

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

NAMES=$@

if [ x"$NAMES" == x"console" ]; then
	usage
	exit -1
fi

for i in $NAMES
do
	ST=`fulcon list | awk '{if ($1 == "'$i'") {if ($2 == "RUNNING"){print 0} else {print 1}}}'`
	if [ x"$ST" != x"0" ]; then
		echo $i "is not running"

	else
		lib-console $OPT_FLG $i
	fi
done

exit 0
