#!/usr/bin/perl
use warnings;
use strict;
use AnyEvent::Redis;
use Data::Dump qw(dump);

use lib 'lib';
use MQR::Redis;

my $track;
my $regex;

MQR::Redis->redis->psubscribe('*', sub {
	my($message, $channel) = @_;
	if ( $channel =~ m/^MSG / ) {
		if ( $message =~ m/^!track\s*(.+)/ ) {
			$track->{$1} = $channel;
			$regex = join('|', keys %$track);
			warn "# track regex: $regex\n";
		} elsif ( $regex && $message =~ m/($regex)/ ) {
			my $found = $1;
			my $body = "TRACK [$found] $channel | $message";
			print "$body\n";
			my $to = $track->{$found} || die "no $1 in ",dump($track);
			$to =~ s/^MSG /SEND /g;
			MQR::Redis->publish( $to, $body );
		}
	} else {
		warn "$channel | $message\n";
	}
});

AnyEvent->condvar->recv;

