#!/usr/perl/bin/perl -w
#
# /msg $botname $oppass - gets you ops on $mychan
# /msg $botname $masterpass rawcommand - sends a raw command

require 5.003;
use Socket;

(-e "pbot.conf") || makeconfig();

conf();


defined($blah = fork()) || die "Can't fork, sorry\n";
($blah) && die "Bot active on process $blah.\n";

while (1) {
 $iaddr = inet_aton($remote);
 $paddr = sockaddr_in($port, $iaddr);
 $proto = getprotobyname('tcp');
 socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "Cannot create socket\n";
 connect(SOCK, $paddr) || die "Unable to connect\n";
 select(SOCK);
 $| = 1;
 select('stdout');  
 print SOCK "USER SB SB SB SB \n";
 print SOCK "NICK $botnick\n";
 while (<SOCK>) {
  ($fulladd,$what,$where,$p4,$p5) = split(/\s/,$_);
  ($nick) = (/^:(.+)!.+\@\S+\s/);
  if ($what =~ /002/) {
   print SOCK "JOIN $joinchan\n";
   next;
  } 
  if (/^PING/) {
   print SOCK "PONG $'\n";
   print SOCK "PRIVMSG $botnick :I ain't idling\n";
   next;
  }
  if ($what =~ /JOIN/) {
   ($where) = ($where =~ /^.(.+)/);
   ($fulladd) = ($fulladd =~ /^.(.+)/);
   autoop();
  }
  if ($what =~ /PRIVMSG/) {
   if ($p4 =~ /:\caVERSION/) {
    print SOCK "NOTICE $nick :\caVERSION Perl Bot - by [SB]Tikiman\n";
    next;
   }
   if ($where =~ /$botnick/i) {
     if ($p4 =~ /:$masterpass/) { 
      ($nmess) = (/^\S+\s\S+\s\S+\s\S+\s(.*)/);
      print SOCK "$nmess\n";
     }
     if ($p4 =~ /:\caPING/) {
      print SOCK "NOTICE $nick :\caPING $p5\n";
      next;
     }
     if ($p4 =~ /^:$oppass/i) {
      print SOCK "MODE $mychan +o $nick\n";
      next; 
     }
    next;
   }
  }
 }
}


sub autoop {
 $gotthere = '';
 open(OPS,"pbot.conf");
 while(<OPS>) {
  chomp;
  if ($gotthere) {
   ($_) || last;
   ($host) = (/^(.*)\s/);
   if (/(\s|,)$where(,|\b)/) {
    iswm($host,$fulladd) && print SOCK "MODE $where +o $nick\n";
   }
  }
  (/^\[autoops\]/) && ($gotthere = 'true');
 }
 close(OPS);
}

#sub autoop {
# open(OPS,"ops");
# while(<OPS>) {
#  chomp;
#
# }
# close(OPS);
#} 

sub iswm {
 ($wild,$host) = @_;
 $wild =~ s/\@([^\*])/\@\.$1/;
 $wild =~ s/\./\\\./g;
 $wild =~ s/\*/\.\*/g;
 $host =~ s/\@(.)/\@\.$1/;
 if ($host =~ /$wild/i) {
  return "yes";
 }
}

sub conf {
 open(CON,"pbot.conf");
 while(<CON>) {
  chomp;
  ($_) || last;
  ($val) = (/.*\s(.*)/);
  (/^remote/) && ($remote = $val);
  (/^port/) && ($port = $val);
  (/^botnick/) && ($botnick = $val);
  (/^mychan/) && ($mychan = $val);
  (/^joinchan/) && ($joinchan = $val);
  (/^oppass/) && ($oppass = $val);
  (/^masterpass/) && ($masterpass = $val);
 }
 close(CON);
}

sub makeconfig {
 open(CONF,">pbot.conf");
 print CONF <<ECN;
[config]
remote irc.blackened.com
port 6667
botnick Whatever
joinchan #channel1,#channel2,#channel3
mychan #channel_for_op_password
oppass pass_for_\$mychan
masterpass SECRETWORD
 
[autoops]
 
ECN
 close(CONF);
 print "Your pbot.conf file has been created.  Please edit this file and restart.\n";
 exit;
}