#!/bin/bash

# Wrap "tm-manifest setnode" with a loop and a stopwatch.  Needs "jq" package.
# Assumes TMMS config is /etc/tmms

echo "DEPRECATED; use tm-manifest setnode ....." >&2 && exit 1

set -u

jq --version >/dev/null 2>&1
[ $? -ne 0 ] && echo "You need to apt-get install jq" >&2 && exit 1

###########################################################################
# Command-line args

[ $# -lt 2 ] && echo "usage: $0 <all | /coord1 [/coordn]> manifest" && exit 1

# Qualify the $NODES
BAD=
if [ $1 = all ]; then
    NODES=`tm-manifest listnodes | jq -r '."200".nodes[]' | sort`
    shift
else
    NODES=
    while [ $# -gt 1 ]; do
	tm-manifest getnode $1 2>/dev/null | grep -q 200
	[ $? -eq 0 ] && NODES="$NODES $1" || BAD="${BAD}No such node $N\n"
	shift
    done
fi
MANIFEST=$1

# Qualify the $MANIFEST
tm-manifest get $MANIFEST | jq -r '."200"' >/dev/null
[ $? -ne 0 ] && BAD="${BAD}\nNo such manifest $MANIFEST"
    
[ "$BAD" ] && echo -e "$BAD" >&2 && exit 1

# Where are status files?
eval `grep 'MANIFESTING_ROOT\s*=' /etc/tmms | tr -d ' 	'`	# space tab
IMAGES=$MANIFESTING_ROOT/tftp/images
[ ! -d "$IMAGES" ] && echo "Cannot find $IMAGES" >&2 && exit 1

###########################################################################
# Pretty-print the time elapsed.  Reset ELAPSED_START as needed.

ELAPSED_START=`date +%s`

function elapsed() {
    END=`date +%s`
    let E=$END-$ELAPSED_START
    let H=$E/3600
    let M=$E/60
    let S=$E%60
    printf "%2d:%02d:%02d" $H $M $S
}

###########################################################################
# Main - start them all

NODECOUNT=0
for N in $NODES; do
	echo $N
	tm-manifest unsetnode $N >/dev/null 2>&1
	tm-manifest setnode $N $MANIFEST	# This status is ok
	let NODECOUNT=NODECOUNT+1
done
echo "`elapsed` all bindings started"

###########################################################################
# Wait until they're all done.  The IMAGES subdirs (nodeXX) are created
# at setup.py networking time, so hopefully the most recent run actually
# matches the current TMCF.

FINISHED=0
while [ $FINISHED -lt $NODECOUNT ]; do
	sleep 5
	FINISHED=`find $IMAGES -name status.json | xargs cat | grep ready | grep status | wc -l`
	echo "`elapsed` $FINISHED/$NODECOUNT bindings finished"
done
exit 0
