#!/usr/bin/env bash
# $Id$
#
# Thomas Dreibholz's PlanetLab Script Collection
# Copyright (C) 2005-2023 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: thomas.dreibholz@gmail.com


. ./planetlab-config


SERVER=$1
if [ x$SERVER = "x" ]; then
   echo "ERROR: No server name/IP given!"
   exit 1
fi



if [ ! -e coredumps/ ]; then
   mkdir coredumps/
fi
cd coredumps/


SERVER_LIST=`\
( \
while [ x$1 != "x" ] ; do \
   echo $1 && \
   shift ; \
done \
) | sort -u`


echo -e "\x1b[34m`date`: Removing old keys ...\x1b[0m"
for SERVER in $SERVER_LIST; do
   echo "Removing key of $SERVER"
   ssh-keygen -R $SERVER >/dev/null 2>&1
done

for SERVER in $SERVER_LIST; do
   echo -e "\x1b[34m`date`: Contacting $SERVER ...\x1b[0m"

   cmd="if [ -e bin/ ] ; then sudo rm -rf bin/ ; fi"

   (
   ssh -i $PLANETLAB_KEY -oStrictHostKeyChecking=no -oPasswordAuthentication=no -oConnectTimeout=30 $PLANETLAB_USER@$SERVER "\
      echo \"\`date\`: Executing clearall on $SERVER ...\" && \
      $cmd ; \
      echo \"\`date\`: $SERVER is ready!\""
   ) &
done

wait
