#!/usr/bin/env perl
use strict;
use warnings;
use POSIX;
use Fcntl;
use NDBM_File;

use vars qw($VERSION %IRSSI);
$VERSION = "1.0";
%IRSSI = (
	authors => "Adam Sampson",
	contact => "ats\@offog.org",
	name => "irssrssi",
	description => "IRC topic to RSS gateway",
	license => "GPLv2",
	url => "",
	changed => "$VERSION",
);

use Irssi;

sub msg($) {
	my ($msg) = @_;
	Irssi::print "\%R<<irssrssi>>\%n $msg", MSGLEVEL_CLIENTCRAP;
}

sub channel_topic {
	my ($c) = @_;

	my $server = $c->{server};
	my $channel = $c->{name};
	$channel =~ s/^#//;
	my $url = "irc://$server->{address}:$server->{port}/$channel";

	$_ = $c->{topic};

	# Remove colours.
	s/\cB//g;
	s/\cC[^\d,]//g;
	s/\cC\d\d?//g;
	s/\cC,\d\d?//g;
	s/\cD[abcdeghi]//g;
	s/\cDf[^,]*,//g;
	s/\cD..//g;
	s/\cF//g;
	s/\cO//g;
	s/\c_//g;

	# Trim whitespace.
	s/^\s+//;
	s/\s+$//;
	s/\s+/ /g;

	my $topic = $_;

	my %data;
	tie %data, "NDBM_File", "$ENV{HOME}/.irssrssi/db",
		O_CREAT | O_RDWR, 0644;
	$data{$url} = int(time()) . ":$topic";
	untie %data;
}

Irssi::signal_add("channel topic changed", "channel_topic");

