#!/usr/local/bin/perl
#
# Use try to connect to an IMAP server, and
# wait for the right output.
#
# For use with "mon".
#
# Arguments are "-p port -t timeout host [host...]"
#
# Adapted from "http.monitor" by
# Jim Trocki, trockij@transmeta.com
#
# http.monitor written by
#
# Jon Meek
# American Cyanamid Company
# Princeton, NJ
#
# $Id: imap.plugin,v 1.2.2.1 2002/07/22 15:21:48 paul-cs 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
#
# Modified by Paul van Tilburg. Speedup needed for Checkservice...
# (removed multiple host support and changed default values)

use Getopt::Std;
use English;
use CS::Functions;

getopts ("p:t:h:");
$Port = $opt_p || 143;
$TIMEOUT = $opt_t || 5;
$Host = $opt_h || "localhost";

exit &imapGET($Host, $Port);

sub imapGET {
  my ($Server, $Port) = @_;
  my $ServerOK = 1;

  eval {
    local $SIG{ALRM} = sub { die "Timeout Alarm" };
    alarm $TIMEOUT;
	
    $sock = opensocket($Server, $Port); # Open a connection to the server
    if (!$sock) { # Failure to open the socket
      return 1;
    }

    $in = <$sock>;
    if ($in !~ /^\* (OK|PREAUTH|BYE)/) {
      alarm 0;
      return 1;
    }

    print $sock "A1 LOGOUT\r\n";

    while (defined($in = <$sock>)) {
      if ($in =~ /^A1 OK/) {
        $ServerOK = 0;
	last;
      }
    }

    close($sock);
    alarm 0; # Cancel the alarm

  };

  if ($EVAL_ERROR and ($EVAL_ERROR =~ /Timeout Alarm/)) {
    return 2;
  }

  return $ServerOK;
}


syntax highlighted by Code2HTML, v. 0.9.1