#!/usr/bin/perl

require 5.002;
use Socket;

use POSIX qw(strftime);

require "jchanbot.cf";

sconnect();
register();
parse();

sub parse {
        while (<SOCK>)
        {
                chomp;
		if ($DEBUG)
		{
			print "<- $_\n";
		}
                if (/^PING :(\S*)/i) {
                        print SOCK "PONG $1\n";
			if ($DEBUG)
			{
				print "-> PONG $1\n";
			}
		} elsif (/^:\S* 381/i) {
			print SOCK "STATS q\n";
			if ($DEBUG)
			{
				print "-> STATS q\n";
			}
		} elsif (/^:\S* 001/i) {
			operup();
		} elsif (/^:\S* 217 \S* q (\S*) (.*)/) {
			# Not case sensitive for this one
			addchan($1, $2);
		} elsif (/^:\S* 219/i) {
			writelog();
			sdisconnect();
		}
        }
}

sub sconnect {
	socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
	if ($use_vhost) {
		$sockaddr = 'S n a4 x8';
		$this = pack($sockaddr, AF_INET,  0, inet_aton($vhost));
		bind(SOCK, $this) || die "bind: $!";
	}
        $iaddr = inet_aton($server) || die "no host: $server";
        $paddr = sockaddr_in($port, $iaddr);
        $proto = getprotobyname('tcp');
        connect(SOCK, $paddr) || die "connect: $!";

        select SOCK; $| = 1;
        select STDOUT;
}

sub register {
	if ($use_pass)
	{
		print SOCK "PASS $spass\n";
		if ($DEBUG)
		{
			print "-> PASS $spass\n";
		}
	}
	print SOCK "NICK $snick\n";
	print SOCK "USER $suser jchanbot jchanbot :$sdesc\n";
	if ($DEBUG)
	{
		print "-> NICK $snick\n";
		print "-> USER $suser jchanbot jchanbot :$sdesc\n";
	}
}

sub openlog {
	my $timeval = time();
	my $timestr = strftime "%Y%m%d%H%M", localtime($timeval);
	open(LOGFILE, ">${logfile}.${timestr}.log");
}

sub closelog {
	close(LOGFILE);
}

sub sdisconnect {
	print SOCK "QUIT :Complete\n";
	if ($DEBUG)
	{
		print "-> QUIT :Complete\n";
	}
	close (SOCK) || die "close: $!";
}

sub operup {
	print SOCK "OPER $onick $opass\n";
	if ($DEBUG)
	{
		print "-> OPER $onick $opass\n";
	}
}

sub addchan {
	my $chan = shift;
	my $reason = shift;
	my $size = @chanlist;
	if ($reason =~ /(.*)\r/)
	{
		$reason = $1;
	}
	$chanlist[$size] = $chan;
	$reasons{$chan} = $reason
}

sub writelog {
	openlog();
	my $size = @chanlist;
	for ($i = 0; $i < $size; $i++) {
		if ($resvfmt)
		{
		    print LOGFILE
		        "/quote RESV $chanlist[$i] $reasons{$chanlist[$i]}\n";
		}
		else
		{
		    print LOGFILE "/quote MODE $chanlist[$i] +j\n";
		}
	}
	closelog();
}

