#!/usr/bin/perl

# Copyright (c) 2004 Alan W. Mahoney. All rights reserved. 
# This program is free software.  You may modify and/or 
# distribute it under the same terms as Perl itself.  
# This copyright notice must remain attached to the file.  

use warnings;
use strict;

use KoLBot;

use KoLBot::ChatMessage;
use KoLBot::FileStateManager;

use KoLBot::Chatbot;
use KoLBot::Chatbot::Rule;
use KoLBot::Chatbot::Action;

use Carp qw( confess );

use POSIX qw ( floor );

my $VERSION=0.5;
my $ID='$Id$';

package Tie::Tee;
sub TIEHANDLE {
  my $class = shift;
  my @handles;
  my $ofh = select();
  for my $path (@_) {
    open(my $fh, ">$path") || die "can't write $path";
    select($fh);
    $|++;
    push @handles, $fh;
  }
  select($ofh);
  bless \@handles,$class;
}

sub PRINT {
  my $self = shift;
  my $ok = 0;
  for my $fh (@$self) {
    $ok += print $fh @_;
  }
  return $ok==@$self;
}

package main;

$SIG{CHLD} = "IGNORE";

my $conf_file;

__FILE__ =~ m|(.*/)(.*)|;
my $FILE = $2;

(@ARGV == 0) and $conf_file = 'catbot.conf';
(@ARGV == 1) and $conf_file = $ARGV[0];
(@ARGV >  1) and 
  die "$FILE requires a configuration file.\n\n" 
  . "$FILE catbot.conf\n";

our ($config,$bconfig1);
# by default, it is in testing mode, and doesn't respond to anyone. Heh.
our $testing = 1;
our $test_user = "";

# Here we could do all kinds of validation and jail stuff, but we don't.
# Let people shoot themselves in the foot with config file if they want.
# Should check at least that file exists, but it'll prolly die if not.
do $conf_file or die;

# We should have a log file, start logging
if($config->{logfile}) {
  tie *STDOUT, "Tie::Tee", ('-','>'.$config->{logfile});
  tie *STDERR, "Tie::Tee", ('-','>'.$config->{logfile});
}

my $myuserid = $bconfig1->{user_id};

# Items, read-only, need one database for all bots.
my $items = new KoLBot::Items(config => { file => 'items.txt'});
$items->init;

# The real bot code.
#
# This example code performs some regex matching and substitution
# and replies to whoever sent it.
# 
# Currently only one partial patern match is allowed, and no quoting.

print $bconfig1->{user}," starting.\n";

my $bot = KoLBot::Chatbot->new(url_i => 2,
			       config => $bconfig1,
			       items=>$items,
#			       db_conf => $config->{db_conf},
			       );

$bot->{sm}  = new KoLBot::FileStateManager(config => 
				      { path => $config->{statedir} } );

#########################################################################
# Rules
#########################################################################

set_rules($bot);

#
# the custom functions return 1 for stop here, or 0 for fall through
# to next rule.  This is likely to be changed that the rule can override
# this in future versions.
#


# $bot->db_connect(\&db_connect);

# things to run before starting: global state

$bot->config->{channel} = $bot->sm->get('!','channel')->{channel};

$bot->main();
# NEVER EXITS, ONLY SUBROUTINES FROM HERE DOWN  

sub set_rules {
  $bot->add_rules
    ( 
      new KoLBot::Chatbot::Rule( iuser => $config->{botnames},
			itype => '.*',
			action => 'log',
				 log => 0,
			),
      # BLACKLIST
      new KoLBot::Chatbot::Rule( iuser => $config->{blacklist},
			itype => '.*',
			action => 'none',
				 log => 0,
			),
# stop it here, don't pm them whatever they say
      new KoLBot::Chatbot::Rule( itype     => '(normal|emote)',
			iuser     => '^(jick|mr skullhead)$',
			action    => 'log',
				 log => 0,
			),
# stuff I advertise, or not
        new KoLBot::Chatbot::Rule ( 
				    itype => 'private',
				    omessage => 'meow',
  			 ),
        new KoLBot::Chatbot::Rule ( 
				    itype => '(normal|emote)',
				    imessage => '\w+\W+catbot(\W|$)',
				    action => 'emote',
				    omessage => ['purrs',
					 'purrs softly',
					 'purrs loudly',
					 'meows',
					 'curls up',
					 'sleeps',
					 'stretches',
					 'runs off mysteriously',
					 'puts on her investigating feet',
					 'preens',
					 'considers the chat',
					 'contemplates her secret name',
#				 'does the Kenyan lion and tiger dance',
					 'stares',],
				    ochannel => '$c',
  			 ),

# specific
      new KoLBot::Chatbot::Rule( itype     => '.*',
			imessage  => '.*',
			action    => 'done',
				 log => 0),
      );
}

sub heartbeat {
  my $bot = shift;
}

