use strict;
use Irssi;
use IO::Handle;
use POSIX;

our $pipe_path = "/tmp/irssi_pipe";
our $pipe_fh;

Irssi::settings_add_str('fifo_input', 'fifo_pipe_path', $pipe_path);

sub fifo_input_open {
    $pipe_path = Irssi::settings_get_str('fifo_pipe_path');
    unless (-p $pipe_path) {
        mkfifo($pipe_path, 0700) or die "Cannot create FIFO pipe: $!";
    }
    
    open($pipe_fh, '<', $pipe_path) or die "Cannot open FIFO pipe: $!";
    $pipe_fh->blocking(0);
    Irssi::input_add(fileno($pipe_fh), Irssi::INPUT_READ, \&fifo_input_read, undef);
}

sub fifo_input_read {
    while (my $line = <$pipe_fh>) {
        chomp $line;
        Irssi::command($line);
    }
}

sub fifo_input_close {
    Irssi::input_remove(fileno($pipe_fh));
    close($pipe_fh);
}

Irssi::signal_add('setup changed', \&fifo_input_open);
Irssi::command_bind('fifo_close', \&fifo_input_close);

fifo_input_open();

Irssi::print("FIFO input script loaded. Listening on $pipe_path");
