use strict;
use Irssi;
use LWP::UserAgent;

my $VERSION = "0.5";
my %IRSSI = (
        authors         => "David O\'Rourke",
        contact         => "phyber\@\#irssi",
        name            => "shortify",
        description     => "Shorten URLs using shortify.com.",
        license         => "GPLv2",
        changed         => "26.06.2005 18:38"
);

my $pipe_tag;
my $shortify_url = 'http://shortify.com/sshorten.php?url=';
my %input = (); # hash for passing data to pipe_input

sub shortify {
	my ($data, $server, $witem) = @_;
	pipe my ($rh,$wh);
	my $pid = fork;
	if(!defined $pid) { # fork failed
		Irssi::print "Couldn't fork, aborting...";
		close($rh); close($wh);
		return;
	}

	# fix URL for shortify if user didn't provide http://
	if ($data ne /^http?:\/\/.*/) { $data = "http://$data"; }
	%input = ('rh', $rh, 'data', $data);
	
	if ($pid > 0) { # parent, wait for the reply
		close($wh);
		Irssi::pidwait_add($pid);
		$pipe_tag = Irssi::input_add(fileno($rh), INPUT_READ, \&pipe_input, %input);
		return;
	}
	
	my $text;

	my $ua = LWP::UserAgent->new;
	$ua->agent("Shortify.pl/0.1 ");
	my $req = HTTP::Request->new(GET => $shortify_url.$data);
	my $res = $ua->request($req);

	if($res->is_success) {
		$text = $res->content;
	} else {
		$text = $res->status_line;
	}
	$text = $! if (!$text);

	# Print text to the write handle
	print($wh $text);
	close($wh);
	
	# Child exits here
	POSIX::_exit(1);
}

# Read the output
sub pipe_input {
	my $rh = $input{'rh'};
	my $data = $input{'data'};
	my $text = <$rh>;
	close($rh);
	chomp($text);

	Irssi::input_remove($pipe_tag);
	$pipe_tag = -1;
	
	my $window = Irssi::active_win();
	$window->print("Shortify: $text ($data)");
	
	#clear the hash, ready for the next round.
	%input = ();
}

Irssi::command_bind('shortify', 'shortify');