#!/bin/sh
#
# Usage: $0 [start [end]]

PATH=`dirname $0`/uml/bin:$PATH

network=`get-uml-config network 192.168.162`
if [ $? -ne 0 ]; then
  echo "Unable to run get-uml-config"
  exit 1
fi
netmask=`get-uml-config netmask 255.255.255.0`
startip=`get-uml-config startip 11`
gateway=`get-uml-config hostip ${network}.1`

if [ "$#" -gt 2 ]
then
  echo "Usage: $0 [start [end]]"
  echo "where start is the first uml to start, eg 1"
  echo "If end is not supplied it is set to 'start'"
  echo "that is: $0 1  means start '1' only"
  echo "If start is not supplied, all devices are started"
  exit 0
fi

case $# in
0) START=0; END=9999;;
1) START="$1"; END="$1";;
2) START="$1"; END="$2";;
esac

# Now at least one version of ping doesn't know -w, so test for that
# (debian's netkit-ping has this silliness, but iputils-ping has -w)
PINGW="-w1"
ping -c 1 $PINGW ${gateway} -q >/dev/null 2>&1
if [ $? -eq 2 ]; then
PINGW=
fi

for i in upro[0-9][0-9][0-9]; do
  if [ ! -f $i/eth0.mac ]; then
    #echo "Directory $i does not contain a UML device, skipping"
    continue
  fi
  NUM=`echo $i | sed -e 's/upro0*//'`
  if [ "$NUM" -lt "$START" ]
  then
    #echo "$i less than range $START-$END: skipping"
    continue
  fi
  if [ "$NUM" -gt "$END" ]
  then
    #echo "$i greater than range $START-$END: skipping"
    continue
  fi
  
  if [ -f $i/linux.pid ]; then 
    kill -0 `cat $i/linux.pid` 2>/dev/null
    if [ $? -eq 0 ]; then
      echo "$i already started"
      continue
    fi
  fi

  # trap sighup and sigint. sort of like nohup.
  #trap "" SIGHUP SIGINT SIGQUIT
  setsid runlinux ${PWD}/$i /dev/null log.out log.err &
  echo -n "Running $i"

  # Wait until we can ping the device

  IP="${network}.$(($NUM + ${startip} - 1))"
  COUNT=0
  while true; do
    ping -c 1 $PINGW -q $IP >/dev/null 2>&1
    if [ $? -eq 0 ]; then
      break;
    fi
    echo -n "."
    COUNT=$(($COUNT + 1))
  done

  echo "started"

  # And wait 1 more second to allow everything to get going
  sleep 1
done
