#!/usr/bin/perl -I/usr/depot/lib/perl5
#
# usage:
#	 echo "psycwake <uni>" | at <time>

use Getopt::Std;
getopt('tbmpn');

print STDERR "This tool uses the new PSYC syntax. Is the server using libpsyc?\n" if $opt_v;

$target  = $opt_t || '127.1';
$method  = $opt_m || '_notice_wake';

$port    = $opt_p || 4404;		# schrott
$nick	 = $opt_n;			#    "

my $text = shift || "You have been $0'd from $ENV{USER}\@$ENV{HOST}.";

if ($target =~ m!^psyc://([^/]+)!i) {
	$remote = $1;
	($remote, $port) = ($1,$2) if $remote =~ m!^([^:]+):(\d+)\b!;
} elsif ($target =~ m:^(\w+)\@(\S+)$:i) {
	$remote = $2;
	$target = "psyc://$remote/~$1";
} else {
	$remote = $target;
	$target = "psyc://$remote";
	$target .= "/~$nick" if $nick;
}

if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') }
die "No port" unless $port;

use Socket;
$iaddr   = inet_aton($remote)			|| die "no host: $remote";
$paddr   = sockaddr_in($port, $iaddr);
socket(S, PF_INET, SOCK_STREAM, getprotobyname('tcp')) || die "socket: $!";

print STDERR "Connecting $port on $remote\n" if $opt_v;

connect(S, $paddr)				|| die "connect: $!";
select S; $|=1; select STDOUT;

print S <<X;
|
X

#if (defined($_ = <S>) && !/^\./) {
#	print if s/^=//;
#}
#while (defined($_ = <S>) && !/^\./) {
#	print if s/^=//;
#}
#print "\n";

print S <<X;
:_target	$target

$method
$text
|

_request_circuit_shutdown
|
X

print STDERR "$method sent to $target\n" if $opt_v;
sleep 2;
close (S)					|| die "close: $!";
sleep 2;
exit;

