#!/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


if [ $# -lt 1 ] ; then
   echo  >&2 "Usage: comon-query [Results File] [Query] [Table Columns] [Sorting] [Format: formatspaces|formatcsv|nameonly]"
   echo  >&2 "Example: comon-query alive.hosts \"resptime>0 && sshstatus<2h && (dns1udp<80 || dns2udp<80)\" name,location name formatspaces"
   exit 1
fi

FILE=$1
QUERY=""
FORMAT=formatspaces
DUMPCOLS=""
SORT=
QUIET=0

if [ "$2" != "" ] ; then
   QUERY=$2
fi
if [ "$3" != "" ] ; then
   DUMPCOLS=$3
fi
if [ "$4" != "" ] ; then
   SORT=$4
fi
if [ "$5" != "" ] ; then
   FORMAT=$5
fi
if [ "$6" == "quiet" ] ; then
   QUIET=1
fi


if [ $QUIET -ne 1 ] ; then
   echo "Querying CoMon ..."
   echo "Results file: $FILE"
   echo "Query:        $QUERY"
   echo "Format:       $FORMAT"
   echo "Dump Columns: $DUMPCOLS"
   echo "Sorted by:    $SORT"
fi

wget -q -O$FILE "http://comon.cs.princeton.edu/status/tabulator.cgi?table=table_nodeviewshort&format=$FORMAT&select='$QUERY'&format=$FORMAT&sort=$SORT&dumpcols='$DUMPCOLS'"

if [ $QUIET -ne 1 ] ; then
   wc --lines $FILE
fi
