use strict;

use Irssi ();
use vars qw($VERSION %IRSSI);

use POSIX ();
use constant BUFSIZ => POSIX::BUFSIZ();
use constant EAGAIN => POSIX::EAGAIN();

use Fcntl ();
use constant O_NONBLOCK => Fcntl::O_NONBLOCK();


$VERSION = '0.1';
%IRSSI = (
    authors	=> 'Arvin Schnell',
    contact	=> 'aschnell@suse.de',
    name	=> 'remote_control',
    description	=> 'irssi remote control',
    license	=> 'GNU GPL',
    url		=> 'http://arvin.schnell-web.net/irssi/',
    changed	=> 'Sat May 31 10:23:42 CEST 2008'
);


# 'Remote Control'. Receives irssi commands on a fifo.
#
# /set remote_control_fifo_path <string>
#       * string : filename of fifo (only used during startup of irssi)
#
# Example usage:
#   echo -e "/set hilight_notify_display $DISPLAY" > ~/.irssi/rc


sub input($)
{
    my ($fh) = @_;

    my $buffer;

    my $ret = sysread($fh, $buffer, BUFSIZ);

    if ((not defined $ret and $! != EAGAIN) or $ret == 0) {
	return;
    }

    return unless $buffer =~ /\n/;

    while ($buffer =~ s/^(.*?)\r?\n//g)
    {
	my $command = $1;

	Irssi::print("Received command \"$command\"");

	if ($command =~ /^\//) {
	    Irssi::active_win()->command($command);
	} else {
	    Irssi::active_win()->command("/say " . $command);
	}
    }
}


sub install_fifo()
{
    my $path = Irssi::settings_get_str('remote_control_fifo_path');

    unlink $path if -S $path and -o $path;
    POSIX::mkfifo($path, 0600);

    my $fh;

    open($fh, "+< " . $path);
    fcntl($fh, O_NONBLOCK, 1);
    Irssi::input_add(fileno $fh, INPUT_READ, 'input', $fh);
}


Irssi::settings_add_str('remote_control', 'remote_control_fifo_path',
			Irssi::get_irssi_dir . '/rc');

install_fifo();