#!/usr/bin/perl
#
# moncmd - send a command to the mon server
#
# -d		debug (sets server and port to localhost, 32768)
# -s server	use server 
# -p port	user port
# -r            raw output; do not format it.
#
# Jim Trocki, trockij@transmeta.com
#
# $Id: moncmd,v 1.17 1998/01/18 17:50:36 trockij Exp $
#
#    Copyright (C) 1998, Jim Trocki
#
#    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 2 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, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
use Getopt::Std;
use Socket;

getopts ("s:p:rd");

$MONSERVER = $ENV{"MONHOST"}
    if (defined ($ENV{"MONHOST"}));

$MONSERVER = $opt_s if ($opt_s);

$MONPORT   = $opt_p || 32777;

if ($opt_d) {
    $MONSERVER = "localhost";
}

if (!defined ($MONSERVER)) {
    die "No host specified or found in MONHOST\n";
}

if (!@ARGV) {
    print <<EOF;

usage: moncmd [-s host] [-p port] commands

Valid commands are:
    exit
    reset
    term
    list group "groupname"
    list disabled
    list alerthist
    list failurehist
    list successes
    list failures
    list opstatus
    list pids
    list watch
    set "group" "service" "variable" "value"
    get "group" "service" "variable"
    disable service "group" "service"
    disable host "host" ["host"...]
    disable watch "watch"
    enable service "group" "service"
    enable host "host" ["host"...]
    enable watch "watch"
EOF
    exit 1;
}

#
# set up TCP socket
#
$iaddr = inet_aton ($MONSERVER);
if ($MONPORT =~ /\D/) { $MONPORT = getservbyname ($MONPORT, 'tcp') }
$paddr = sockaddr_in ($MONPORT, $iaddr);
$proto = getprotobyname ('tcp');

socket (MON, PF_INET, SOCK_STREAM, $proto) ||
    die "could not create socket: $!\n";
connect (MON, $paddr) ||
    die "could not connect: $!\n";

select (MON); $| = 1; select (STDOUT);

#
# send the command, shut down sends
#
print MON "@ARGV\n";
shutdown (MON, 1) ||
    die "could not shutdown: $!\n";

#
# suck in the output
#
while (<MON>) {
    print;
}

close(MON);
