#! /usr/bin/env perl
use lib ($ENV{RLWRAP_FILTERDIR} or ".");
use RlwrapFilter;
use strict;

my $filter = new RlwrapFilter;
my $name = $filter->name;

$filter->help_text("Usage: rlwrap -z '$name <filter-command> [<filter-command-args> ... ]' <command>\n"
                   . "Filter <command> output through <filter-command>\n"
                   . "e.g. 'rlwrap  -z \"outfilter grep -E --color 'blah|\$'\" command' will colour all blah's in commands output");


# prevent quoting headaches
foreach my $arg (@ARGV) {
    $arg = "'$arg'";
    print("$arg\n");
}

my $filter_command = join ' ', @ARGV;
die $filter -> help_text . "\n" if not $filter_command and $ENV{RLWRAP_COMMAND_PID};

$filter->output_handler(sub {""});
$filter->prompt_handler(\&prompt);

print("BLA\n");


$filter->run;

sub prompt {
    my $prompt = shift;
    print("BLO\n");

    my $output = $filter->cumulative_output;
    $output =~ s/\r//g;
    print("filter_command: <$filter_command>\n");
    open (PIPE, "| $filter_command")
        or die "Failed to create pipe: $!";
    print PIPE $output;
    close PIPE;

    return $prompt;
}
