#!/usr/bin/perl
use strict;
use Getopt::Std;
use IO::Socket; # warning - IO::Socket was an optional add-on prior to 5.004

my $host = "127.0.0.1";
my $port = 17777;
my $timeout = 10;
our(%Opts);

my $Usage = "Usage: $0 [-i ipaddr] [-p port] command\n";

# argv check
getopts('i:p:', \%Opts) or die "$Usage";
my $command = shift(@ARGV);
if ($ARGV[-1] ne "") {
    print $Usage;
    exit(1);
}

# command check
if ($command ne "reload") {
    print $Usage;
    exit(1);
}

# ipaddr check
if ($Opts{'i'} ne "") {
    if ($Opts{'i'} =~ /^\d+\.\d+\.\d+\.\d+$/) {
	$host = $Opts{'i'};
    } else {
	print $Usage;
	exit(1);
    }
}

# port check
if ($Opts{'p'} ne "") {
    if ($Opts{'p'} > 0 && $Opts{'p'} < 65536) {
	$port = $Opts{'p'};
    } else {
	print $Usage;
	exit(1);
    }
}
    
# connnect messasy
my $sock = IO::Socket::INET->new(
                Proto => "tcp",
                PeerAddr => $host,
                PeerPort => $port,
                Timeout => $timeout)
        # I've found "$!" to be very unhelpful in the following
        or die "$0: socket failed: cannot connect to $host\n";

# get response
my $buf = <$sock>;	# $buf: Welcome to messasy

# send command
print $sock "$command\n";

$buf = <$sock>;		# $buf: +OK or -NG
chomp $buf;

if ($buf !~ /OK/) {
    print "$command failed\n";
    print $sock "exit\n";
    exit(1);
}

print "$command successful\n";
print $sock "exit\n";
exit(0);
