#!/usr/bin/perl

$me = "ventz\@vpetkov.net";
$me_chat = "ventz";
$tinyurltrigger = 40;

$event = $ARGV[0];
$arg = $ARGV[1];
$jid = $ARGV[2];
$filename = $ARGV[3];

# Exit unless it's a type MSG and it's incoming!
exit unless ( ($event eq 'MSG') && ($arg eq 'IN' || $arg eq 'MUC') && ( ($jid ne $me) || ($jid ne $me_chat) ) );


$msg = `cat $filename`;
#`rm -f "$filename"`;
unlink "$filename";

if($msg =~ /(\w+:\/\/\S+)/) {
	my @text = split(" ", $msg);
	for my $link (@text) {
		if($link =~ /(\w+:\/\/\S+)/) {
			chomp($link);
			$size = length($link);
			if($size >= $tinyurltrigger) {
				eval {
					my $alarm = 5;
					alarm $alarm;
					$tinyurl=`wget -q -O - http://tinyurl.com/api-create.php?url="$link"`;
					alarm 0;
				};

				if ($@) {
					#print STDERR "COULD NOT GET LINK\n";
				}
				else {

					#`echo "$link" > ~/.mcabber/VENTZ`;
					#`echo "$tinyurl" >> ~/.mcabber/VENTZ`;
					#`echo "say_to -q -h $me <= $jid $link" > ~/.mcabber/mcabber.fifo`;
					`echo "/say_to -q $jid $tinyurl (BOT: URL SHORTENED)" > ~/.mcabber/mcabber.fifo`;
				}
			}
		}
	}
}

exit 0;
