#!/bin/bash

# Start multiple FAME nodes.
# Args are "all" or a list of nodenumbers range 1-40.

###########################################################################
# Help processing.

if [ $# -eq 0 -o "$1" = "-?" ]; then
	echo "usage: $0 all | nodenum [nodenum...]"
	exit 0
fi

[ `whoami` != root ] && sudo echo	# establish hysteresis

###########################################################################
# What's already running?

N=`pgrep -a qemu-system-aar | grep $NETNAME | wc -l` 
[ $N -ne 0 ] && echo "$N node(s) already running on $NETNAME" >&2 && exit 1

SCREEN=`screen -list | grep $NETNAME`
[ "$SCREEN" ] && echo "screen is already running $SCREEN" >&2 && exit 1

[ -z "$NETNAME" ] && echo "export NETNAME=something" >&1 && exit 1
ip link show $NETNAME >/dev/null 2>&1
[ $? -ne 0 ] && echo "Link $NETNAME does not exist" >&2 && exit 1
[ -z "$FAM" ] && echo "export FAM=something" >&1 && exit 1
[ "$FAM" != NONE -a ! -f "$FAM" ] && echo "Cannot find FAM=$FAM" >&2 && exit 1

###########################################################################
# Command line processing.

if [ $1 = all ]; then
    # Use manifesting service to walk through all nodes ready to run.
    jq --version >/dev/null 2>&1
    [ $? -ne 0 ] && echo "You need to apt-get install jq" >&2 && exit 1

    NODE_COORDS=`tm-manifest listnodes | jq -r '."200".nodes[]'`
    # echo $NODE_COORDS

    echo -n 'Building list of "ready" nodes:'
    NODES=
    for N in $NODE_COORDS; do
        TEMP=`tm-manifest getnode $N`
        STATUS=`echo $TEMP | jq -r '."200".status'`
	[ "$STATUS" != ready ] && continue
        NODE_ID=`echo $TEMP | jq -r '."200".node_id'`
	echo -n " $NODE_ID"
	NODES="$NODES $NODE_ID"
    done
    echo
else
    NODES="$@"	# These aren't qualified in any way
fi

set -u

STARTNODE=startnode.arm		# Hardcoded now; in the future, who knows?

###########################################################################
# Go.  

screen -S $NETNAME -dm		# Session name, detached
echo -n Starting
for N in $NODES; do
	echo -n " $N"
	TITLE=node`printf "%02d" $N`
	screen -S $NETNAME -X screen -t $TITLE $STARTNODE $N
	# Staggering the start helps.  0, 1, or 2 seconds, it doesn't matter:
	# starting 40 nodes takes 4 minutes total.  All that changes is 
	# waitnodes elapsed time.  1 second made 200 perfect runs, so...
	sleep 2		# ...to allow for multiple containers on the SD.
done
echo
echo "Attach nodeXX from shell:    attachnode XX"
echo "Prompt for window name:      ctl-a then '"
echo "Navigate list of windows:    ctl-a then \""
echo "Quit (detach):               ctl-a then d"
sleep 3

exec waitnodes $NODES
