#! /bin/sh
# determine the cores currently available
# last modified 14 Oct 08 th

# usage:  findcores [-f rcfile] [-m maxcpus] [-h ruptimehost]


while [ $# -gt 0 ] ; do
  case $1 in
  -f) rcfile=$2 ;;
  -m) maxcpus=$2 ;;
  -h) ruptimehost=$2 ;;
  *)  ;;
  esac
  shift 2
done

[ -t 0 ] || read maxcpus

[ -z "$maxcpus" -o "$maxcpus" = Infinity ] && maxcpus=10000

if [ -z "$rcfile" ] ; then
  rcfile=.submitrc
  [ -f $rcfile ] || rcfile=$HOME/.submitrc
  [ -f $rcfile ] || rcfile=`dirname $0`/submitrc
  [ -f $rcfile ] || rcfile=/usr/local/share/submitrc
fi

if [ ! -f $rcfile ] ; then
  echo "No .submitrc file found" 1>&2
  exit 1
fi


readrc()
{
  ruptime=`[ -n "$ruptimehost" ] && ssh $ruptimehost ruptime || ruptime`
  while read host cpus ignore ; do
    case "$host" in
    "" | \#* | nice) ;;
    *)
      cpus=${cpus:-1}
      [ -z "$uptimes" ] || cpus=`echo "$uptimes" | \
        awk "/^$host *up/ {print int($cpus - \\$7 + .5)}"`
      while [ $cpus -gt 0 ] ; do
        echo "\"$host\", "
        cpus=`expr $cpus - 1`
        maxcpus=`expr $maxcpus - 1`
        [ "$maxcpus" -le 0 ] && return
      done
    esac
  done
}


echo '{'
cat $rcfile | readrc
echo 'Sequence[]}'

