#!/usr/bin/env bash
# $Id$
#
# Thomas Dreibholz's PlanetLab Script Collection
# Copyright (C) 2005-2022 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: dreibh@iem.uni-due.de


. ./planetlab-config


showbad=0
showhosts=0


SERVER_TEST_OUTPUT=/dev/null
SERVER_LIST=""
while [ x$1 != "x" ] ; do \
   arg=`echo $1 | grep -- "^-"`
   if [ "x$arg" = "x" ] ; then
      SERVER_LIST="$SERVER_LIST $1"
   else
      if [ "x$1" = "x-showbad" ] ; then
         showbad=1
      elif [ "x$1" = "x-showhosts" ] ; then
         showhosts=1
      elif [ "x$1" = "x-showoutput" ] ; then
         SERVER_TEST_OUTPUT=/dev/stderr
      elif [ "x$1" = "x-timeout" ] ; then
         SERVER_TEST_TIMEOUT=$2
         shift
      else
         echo "ERROR: Bad parameter $1"
         exit 1
      fi
   fi
   shift
done
SERVER_LIST=`echo $SERVER_LIST | xargs -xn1 | sort -u`


good=0
bad=0
for SERVER in $SERVER_LIST; do
   isgood=0
   if [ $showhosts = 1 ] ; then
      echo "# Testing $SERVER ..."
   fi
   ../execalarm $SERVER_TEST_TIMEOUT "ssh -C -i $PLANETLAB_KEY -oConnectTimeout=120 -oStrictHostKeyChecking=no -oPasswordAuthentication=no $PLANETLAB_USER@$SERVER \"$SERVER_TEST && echo \\\"$SERVER is ready!\\\"\"" 1>$SERVER_TEST_OUTPUT 2>$SERVER_TEST_OUTPUT
   result=$?
   if [ $result -eq 0 ]  ; then
      isgood=1
   fi

   if [ $isgood = 1 ] ; then
      echo "$SERVER"
      let "good+=1"
   else
      if [ $showbad = 1 ] ; then
         echo "# --- $SERVER"
      fi
      let "bad+=1"
   fi
done

if [ $showbad = 1 ] ; then
   echo "# Good: $good   Bad: $bad"
fi

if [ $bad -gt 0 ] ; then
   exit 1
fi
