#! /usr/bin/perl -w
use diagnostics;
use strict;

use Net::IRC;

sub usage ()
{
	die <<"EOF";
Usage: $0 server bot-name target-channel
EOF
}

my %tasks = ();

my $server = shift or usage;
my $botname = shift or usage;
my $channel = shift or usage;

my $irc = new Net::IRC;

my $conn = $irc->newconn(Nick => $botname, Server => $server)
	or die "$0: can't connect to IRC server";

my $joined = 0;

sub on_connect
{
	my $self = shift;
	$self->join($channel);
}

sub on_topic
{
	my $self = shift;
	$joined = 1;
}

sub on_public
{
	my ($self, $event) = @_;
	my ($args) = $event->args;
	my $from = $event->from;
	$from =~ s/!.*//;
	if ($args =~ s/^$botname:?\s*//io)
	{
		my ($victim, $task, $tasksref);
		(my $command, $args) = split ' ', $args, 2;
		$command = lc $command;
		if ($command eq 'add' && $args =~ /^([^ \t]+)\s+(.*[^ \t])/)
		{
			($victim, $task) = ($1, $2);
			$tasksref = $tasks{$victim};
			$tasksref = $tasks{$victim} = [] if not defined $tasksref;
			$$tasksref[scalar @$tasksref] = $task;
			$self->privmsg($channel, "cheers, added task for $victim:");
			$self->privmsg($channel, "  $task");
		}
		elsif ($command eq 'delete' && $args =~ /^([^ \t]+)\s+(.*[^ \t])/)
		{
			($victim, $task) = ($1, $2);
			$tasksref = $tasks{$victim};
			if (defined $tasksref && scalar grep {$_ eq $task} @$tasksref)
			{
				@$tasksref = grep {$_ ne $task} @$tasksref;
				$self->privmsg($channel, "cheers, deleted task for $victim:");
				$self->privmsg($channel, "  $task");
			}
			else
			{
				$self->privmsg($channel,
							   "sorry, never heard of that task for $victim:");
				$self->privmsg($channel, "  $task");
			}
		}
		elsif ($command eq 'deleteall' && $args =~ /^([^ \t]+)/)
		{
			$victim = $1;
			undef $tasks{$victim};
			$self->privmsg($channel, "$victim is free! For a short time ...");
		}
		elsif ($command eq 'help')
		{
			$self->privmsg($channel, "No.");
		}
		elsif ($command eq 'list' && $args =~ /^([^ \t]+)/)
		{
			$victim = $1;
			$tasksref = $tasks{$victim};
			if (defined $tasksref && scalar @{$tasks{$victim}})
			{
				$self->privmsg($channel, "$victim is supposed to be doing:");
			}
			else
			{
				$self->privmsg($channel, "No tasks for $victim.");
			}
			foreach my $task (@{$tasks{$victim}})
			{
				$self->privmsg($channel, "  $task");
			}
		}
		elsif ($command eq 'quit')
		{
			$self->privmsg($channel, "They killed $botname! The bastards ...");
			$self->quit;
			exit;
		}
	}
}

$conn->add_handler('376', \&on_connect);
$conn->add_handler('332', \&on_topic);
$conn->add_handler('public', \&on_public);

$irc->start;
