#!/bin/bash
default_image="orbit-parallel"

# Set up pxe links on repository2 for pxe boot

nodeset=""
sub=`/sbin/ifconfig eth1 | grep 'inet addr' | cut -c21-26`
processLine_before(){
line="$@" # get all args
echo $line > node
node_x=`cut -f1 -d',' node`
node_y=`cut -f2 -d',' node`
node_id="node"$node_x"-"$node_y
subnet_ip=$sub$node_x"."$node_y
echo "My subnet number is $subnet_ip"
wget -O - "http://pxe:5012/pxe/setBootImage?img=$default_image&node=$node_id&ip=$subnet_ip"
# Reset the selected nodes using cmc service
wget -O - "http://cmc:5012/cmc/on?x=$node_x&y=$node_y"
wget -O - "http://cmc:5012/cmc/reset?x=$node_x&y=$node_y"
nodeset=$nodeset" "$node_id
}
 
processLine_after(){
line="$@" # get all args
echo "$line" > node
node_x=`cut -f1 -d',' node`
node_y=`cut -f2 -d',' node`
node_id="node"$node_x"-"$node_y
subnet_ip=$sub$node_x"."$node_y
wget -O - "http://pxe:5012/pxe/clearBootImage?node=$node_id&ip=$subnet_ip"
wget -O - "http://cmc:5012/cmc/reset?x=$node_x&y=$node_y"
} 
cp $1 /usr/$1
processLine_gexec(){
line="$@" # get all args
echo "$line" > node
node_x=`cut -f1 -d',' node`
node_y=`cut -f2 -d',' node`
node_id="node"$node_x"-"$node_y
export GEXEC_SVRS="$node_id"
subnet_ip=$sub$node_x"."$node_y
cd /usr
gexec -n 0 frisbee -p $port -m $multicast -i $subnet_ip /dev/hda &
}


FILE=""
# Make sure we get file name as command line argument
# Else read it from standard input device
if [ "$1" == "" ]; then
FILE="/dev/stdin"
else
FILE="$1"
# make sure file exist and readable
if [ ! -f $FILE ]; then
echo "$FILE : does not exists"
exit 1
elif [ ! -r $FILE ]; then
echo "$FILE: can not read"
exit 2
fi
fi
# read $FILE using the file descriptors
exec 3<&0
exec 0<$FILE
while read line
do
# use $line variable to process line in processLine() function
processLine_before $line
done
echo "$nodeset"
exec 0<&3

sleep 120

# Launch the frisbee server
export LD_ASSUME_KERNEL="2.4.2"
wget -O - "http://frisbee:5012/frisbee/getAddress?img=$2"  > PORT

port=`cut -c 11-15 PORT`
multicast=`cut -c 0-9 PORT`
FILE="$1"
exec 3<&0
exec 0<$FILE
while read line
do
#use $line variable to process line in processLine() function
processLine_gexec $line
done

sleep 380

#sleep 180
#export GEXEC_SVRS="$nodeset"
#export LD_ASSUME_KERNEL="2.4.2"
#cd /etc
#gexec -n 0 frisbee -p $port -m 224.0.0.2 -i $subnet_ip /dev/hda

FILE="$1"
exec 3<&0
exec 0<$FILE
while read line
do
# use $line variable to process line in processLine() function
processLine_after $line
done


function usage()
{
echo "Usage: $0 {atheros|intel|all} image_file_path" >&2
echo "for example:" >&2
echo "   $0 all tmp/image-tridencom-test.ndz" >&2
}
if [ $# -ne 2 ]
then
echo "ERROR: Wrong number of arguments: $1"
usage
exit 1
fi
