#!/usr/bin/perl

use Net::IRC;
use Fcntl;

$fpath = '/tmp/agi-irc-irc.pipe';
$nick = '';
$server = '';
$port = 6667;
$ircname = '';
$username = '';
my $chan = '';

unless (-p $fpath) {
    if (-e _) {
        die "$fpath exists but is not a named pipe.  Will not overwrite.  Exiting.\n";
    } else {
        require POSIX;
        POSIX::mkfifo($fpath, 0666) or die "can't mknod $fpath: $!";
    }
}

$irc = new Net::IRC;
  $conn = $irc->newconn(Nick     => $nick,
                        Server   => $server,
                        Port     => $port,
                        Ircname  => $ircname,
                        Username => $username,
);

sub onConnect {
  $self=shift;
  $self->join($chan);
}

sub onRequest {
        my ($conn, $event)=@_;
        my $enick=$event->nick;
        my $text=$event->{args}[0];
	die "Pipe file disappeared" unless -p $fpath;
	sysopen(FIFO, $fpath, O_WRONLY) or die "can't write $fpath: $!";
	print FIFO $text, "\n";
	close FIFO;
	select(undef, undef, undef, 0.2);
}

$conn->add_handler('public', \&onRequest);
$conn->add_handler('376', \&onConnect);
$irc->start;
