]> git.donarmstrong.com Git - infobot.git/blobdiff - src/IRC/Schedulers.pl
- added CR's here and there; minor reformatting
[infobot.git] / src / IRC / Schedulers.pl
index c5d1017a9a4eb5a55fb3d35f5abb8cdb16c04651..25544e9f4edb62df9befc5b2857aaf5faffecf4a 100644 (file)
@@ -10,17 +10,13 @@ if (&IsParam("useStrict")) { use strict; }
 use POSIX qw(strftime);
 use vars qw(%sched);
 
-#
-# is there a point in ScheduleChecked()?
-# not yet... not unless we run setupSchedulers more than once.
-#
-
 sub setupSchedulers {
     &VERB("Starting schedulers...",2);
 
     # ONCE OFF.
 
     # REPETITIVE.
+    # 1 for run straight away, 2 for on next-run.
     &uptimeLoop(1);
     &randomQuote(2);
     &randomFactoid(2);
@@ -29,23 +25,28 @@ sub setupSchedulers {
     &chanlimitCheck(1);
     &netsplitCheck(1); # mandatory
     &floodLoop(1);     # mandatory
-    &seenFlush(1);
-    &leakCheck(1);     # mandatory
+    &seenFlush(2);
+    &leakCheck(2);     # mandatory
     &ignoreCheck(1);   # mandatory
-    &seenFlushOld(1);
-    &ircCheck(1);      # mandatory
+    &seenFlushOld(2);
+    &ircCheck(2);      # mandatory
     &miscCheck(1);     # mandatory
+    &miscCheck2(2);    # mandatory
     &shmFlush(1);      # mandatory
     &slashdotLoop(2);
     &freshmeatLoop(2);
     &kernelLoop(2);
-    &wingateWriteFile(1);
+    &wingateWriteFile(2);
     &factoidCheck(1);
+    &newsFlush(1);
 
 #    my $count = map { exists $sched{$_}{TIME} } keys %sched;
     my $count  = 0;
     foreach (keys %sched) {
-       next unless (exists $sched{$_}{TIME});
+#      next unless (exists $sched{$_}{TIME});
+       my $time = $sched{$_}{TIME};
+       next unless (defined $time and $time > time());
+
        $count++;
     }
 
@@ -62,28 +63,18 @@ sub ScheduleThis {
        return;
     }
 
-    if (exists $sched{$codename}{RUNNING}) {
-       &WARN("Sched for $codename already exists. forgot ScheduleChecked?");
+    my $time = $sched{$codename}{TIME};
+    if (defined $time and $time > time()) {
+       &WARN("Sched for $codename already exists.");
        return;
     }
 
-    &VERB("Scheduling \&$codename() for ".&Time2String($waittime),3);
+#    &VERB("Scheduling \&$codename() for ".&Time2String($waittime),3);
+
     my $retval = $conn->schedule($waittime, \&$codename, @args);
     $sched{$codename}{LABEL}   = $retval;
     $sched{$codename}{TIME}    = time()+$waittime;
-    $sched{$codename}{RUNNING} = 1;
-}
-
-sub ScheduleChecked {
-    my ($codename) = shift;
-
-    # what the hell is this for?
-    if (exists $sched{$codename}{RUNNING}) {
-###    &DEBUG("SC: Removed $codename.");
-       delete $sched{$codename}{RUNNING};
-    } else {
-###    &WARN("sched $codename already removed.");
-    }
+    $sched{$codename}{LOOP}    = 1;
 }
 
 ####
@@ -94,7 +85,6 @@ sub randomQuote {
     my $interval = &getChanConfDefault("randomQuoteInterval", 60);
     if (@_) {
        &ScheduleThis($interval, "randomQuote");
-       &ScheduleChecked("randomQuote");
        return if ($_[0] eq "2");       # defer.
     }
 
@@ -105,7 +95,7 @@ sub randomQuote {
     }
 
     foreach ( &ChanConfList("randomQuote") ) {
-       next unless (&validChan($_));   # ???
+       next unless (&validChan($_));
 
        &status("sending random Quote to $_.");
        &action($_, "Ponders: ".$line);
@@ -121,14 +111,14 @@ sub randomFactoid {
     my $interval = &getChanConfDefault("randomFactoidInterval", 60);
     if (@_) {
        &ScheduleThis($interval, "randomFactoid");
-       &ScheduleChecked("randomFactoid");
        return if ($_[0] eq "2");       # defer.
     }
 
     while (1) {
        ($key,$val) = &randKey("factoids","factoid_key,factoid_value");
 ###    $val =~ tr/^[A-Z]/[a-z]/;       # blah is Good => blah is good.
-       last if ($val !~ /^</);
+       last if (defined $val and $val !~ /^</);
+
        $error++;
        if ($error == 5) {
            &ERROR("rF: tried 5 times but failed.");
@@ -137,7 +127,7 @@ sub randomFactoid {
     }
 
     foreach ( &ChanConfList("randomFactoid") ) {
-       next unless (&validChan($_));   # ???
+       next unless (&validChan($_));
 
        &status("sending random Factoid to $_.");
        &action($_, "Thinks: \037$key\037 is $val");
@@ -151,7 +141,6 @@ sub randomFreshmeat {
 
     if (@_) {
        &ScheduleThis($interval, "randomFreshmeat");
-       &ScheduleChecked("randomFreshmeat");
        return if ($_[0] eq "2");       # defer.
     }
 
@@ -162,7 +151,7 @@ sub randomFreshmeat {
        my $retval = &Freshmeat::randPackage();
 
        foreach (@chans) {
-           next unless (&validChan($_));       # ???
+           next unless (&validChan($_));
 
            &status("sending random Freshmeat to $_.");
            &say($_, $line);
@@ -173,7 +162,6 @@ sub randomFreshmeat {
 sub logLoop {
     if (@_) {
        &ScheduleThis(60, "logLoop");
-       &ScheduleChecked("logLoop");
        return if ($_[0] eq "2");       # defer.
     }
 
@@ -199,7 +187,7 @@ sub logLoop {
        }
 
        &closeLog();
-       system("/bin/mv '$param{'logfile'}' '$file{log}'");
+       CORE::system("/bin/mv '$param{'logfile'}' '$file{log}'");
        &compress($file{log});
        &openLog();
        &status("cycling log file.");
@@ -246,7 +234,6 @@ sub logLoop {
 sub seenFlushOld {
     if (@_) {
        &ScheduleThis(1440, "seenFlushOld");
-       &ScheduleChecked("seenFlushOld");
        return if ($_[0] eq "2");       # defer.
     }
 
@@ -254,8 +241,8 @@ sub seenFlushOld {
     return unless (&IsChanConf("seen") > 0);
     return unless (&IsChanConf("seenFlushInterval") > 0);
 
-    my $max_time = ($chanconf{_default}{'seenMaxDays'} || 30)
-                               *60*60*24; # global.
+    # global setting. does not make sense for per-channel.
+    my $max_time = &getChanConfDefault("seenMaxDays", 30) *60*60*24;
     my $delete   = 0;
 
     if ($param{'DBType'} =~ /^pg|postgres|mysql/i) {
@@ -288,35 +275,143 @@ sub seenFlushOld {
 
 }
 
+sub newsFlush {
+    if (@_) {
+       &ScheduleThis(60, "newsFlush");
+       return if ($_[0] eq "2");       # defer.
+    }
+
+    if (&ChanConfList("news")) {
+    } else {
+       &DEBUG("newsFlush: news disabled? (chan => $chan)");
+       return;
+    }
+
+    my $delete = 0;
+    my $oldest = time();
+    my %none;
+    foreach $chan (keys %::news) {
+       my $i           = 0;
+       my $total       = scalar(keys %{ $::news{$chan} });
+
+       &DEBUG("newsFlush: chan => $chan (total => $total)");
+
+       foreach $item (keys %{ $::news{$chan} }) {
+           my $t = $::news{$chan}{$item}{Expire};
+
+           my $tadd    = $::news{$chan}{$item}{Time};
+           $oldest     = $tadd if ($oldest > $tadd);
+
+           next if ($t == 0 or $t == -1);
+           if ($t < 1000) {
+               &status("newsFlush: Fixed Expire time for $chan/$item, should not happen anyway.");
+               $::news{$chan}{$item}{Expire} = time() + $t*60*60*24;
+               next;
+           }
+
+           my $delta = $t - time();
+
+           next unless (time() > $t);
+
+           # todo: show how old it was.
+           delete $::news{$chan}{$item};
+           &status("NEWS: (newsflush) deleted '$item'");
+           $delete++;
+           $i++;
+       }
+
+       &status("NEWS (newsflush) {$chan}: deleted [$i/$total] news entries.");
+       $none{$chan} = 1 if ($total == $i);
+    }
+
+    # todo: flush users aswell.
+    my $duser  = 0;
+    foreach $chan (keys %::newsuser) {
+       next if (exists $none{$chan});
+
+       foreach (keys %{ $::newsuser{$chan} }) {
+           my $t = $::newsuser{$chan}{$_};
+           if (!defined $t or ($t > 2 and $t < 1000)) {
+               &DEBUG("something wrong with newsuser{$chan}{$_} => $t");
+               next;
+           }
+
+           next unless ($oldest > $t);
+
+           delete $::newsuser{$chan}{$_};
+           $duser++;
+       }
+
+       my $i = scalar(keys %{ $::newsuser{$chan} });
+       delete $::newsuser{$chan} unless ($i);
+    }
+
+    if ($delete or $duser) {
+       &DEBUG("newsF: Writing news.");
+       &News::writeNews();
+       &status("NEWS (newsflush) deleted: $delete news entries; $duser user cache.");
+    }
+}
+
 sub chanlimitCheck {
+    my $interval = &getChanConfDefault("chanlimitcheckInterval", 10);
+
     if (@_) {
-       my $interval = &getChanConf("chanlimitcheckInterval") || 10;
        &ScheduleThis($interval, "chanlimitCheck");
-       &ScheduleChecked("chanlimitCheck");
        return if ($_[0] eq "2");
     }
 
-    foreach ( &ChanConfList("chanlimitcheck") ) {
-       next unless (&validChan($_));   # ???
+    foreach $chan ( &ChanConfList("chanlimitcheck") ) {
+       next unless (&validChan($chan));
+
+       my $limitplus   = &getChanConfDefault("chanlimitcheckPlus", 5, $chan);
+       my $newlimit    = scalar(keys %{ $channels{$chan}{''} }) + $limitplus;
+       my $limit       = $channels{$chan}{'l'};
+
+       if (scalar keys %netsplitservers) {
+           if (defined $limit) {
+               &DEBUG("chanlimit: removing it for $chan.");
+               &rawout("MODE $chan -l");
+               $cache{chanlimitChange}{$chan} = time();
+           }
 
-       my $limitplus   = &getChanConf("chanlimitcheckPlus",$_) || 5;
-       my $newlimit    = scalar(keys %{$channels{$_}{''}}) + $limitplus;
-       my $limit       = $channels{$_}{'l'};
+           next;
+       }
 
-       if (scalar keys %{$channels{$_}{''}} > $limit) {
-           &status("LIMIT: set too low!!! FIXME");
+       if (defined $limit and scalar keys %{ $channels{$chan}{''} } > $limit) {
+           &FIXME("LIMIT: set too low!!! FIXME");
            ### run NAMES again and flush it.
        }
 
-       next unless (!defined $limit or $limit != $newlimit);
+       next unless (!defined $limit);
+       if (defined $limit and $limit == $newlimit) {
+           $cache{chanlimitChange}{$chan} = time();
+           next;
+       }
 
-       if (!exists $channels{$_}{'o'}{$ident}) {
-           &ERROR("chanlimitcheck: dont have ops on $_.");
+       if (!exists $channels{$chan}{'o'}{$ident}) {
+           &status("ChanLimit: dont have ops on $chan.") unless (exists $cache{warn}{chanlimit}{$chan});
+           $cache{warn}{chanlimit}{$chan} = 1;
+           &chanServCheck($chan);
            next;
        }
-       &rawout("MODE $_ +l $newlimit");
-    }
+       delete $cache{warn}{chanlimit}{$chan};
+
+       if (!defined $limit) {
+           &status("ChanLimit: setting for first time or from netsplit, for $chan");
+       }
 
+       if (exists $cache{chanlimitChange}{$chan}) {
+           my $delta = time() - $cache{chanlimitChange}{$chan};
+           if ($delta < $interval*60) {
+               &DEBUG("not going to change chanlimit! ($delta<$interval*60)");
+               return;
+           }
+       }
+
+       &rawout("MODE $chan +l $newlimit");
+       $cache{chanlimitChange}{$chan} = time();
+    }
 }
 
 sub netsplitCheck {
@@ -324,31 +419,49 @@ sub netsplitCheck {
 
     if (@_) {
        &ScheduleThis(30, "netsplitCheck");
-       &ScheduleChecked("netsplitCheck");
        return if ($_[0] eq "2");
     }
 
+    &DEBUG("running netsplitCheck...");
+
     foreach $s1 (keys %netsplitservers) {
-       foreach $s2 (keys %{$netsplitservers{$s1}}) {
+       &DEBUG("nsC: s1 => $s1");
+
+       foreach $s2 (keys %{ $netsplitservers{$s1} }) {
+           my $delta = time() - $netsplitservers{$s1}{$s2};
+           &DEBUG("nss{$s1}{$s2} = $delta");
+
            if (time() - $netsplitservers{$s1}{$s2} > 3600) {
                &status("netsplit between $s1 and $s2 appears to be stale.");
                delete $netsplitservers{$s1}{$s2};
            }
        }
+
+       my $i = scalar(keys %{ $netsplitservers{$s1} });
+       delete $netsplitservers{$s1} unless ($i);
     }
 
     # %netsplit hash checker.
+    my $count  = scalar keys %netsplit;
     foreach (keys %netsplit) {
        if (&IsNickInAnyChan($_)) {
            &DEBUG("netsplitC: $_ is in some chan; removing from netsplit list.");
            delete $netsplit{$_};
+           next;
        }
-       next unless (time() - $netsplit{$_} > 60*60*2); # 2 hours.
-       next if (&IsNickInAnyChan($_));
+       next unless (time() - $netsplit{$_} > 60*10);
 
-       &DEBUG("netsplitC: $_ didn't come back from netsplit in 2 hours; removing from netsplit list.");
+       &DEBUG("netsplitC: $_ didn't come back from netsplit; removing from netsplit list.");
        delete $netsplit{$_};
     }
+
+    &DEBUG("nsC: netsplitservers: ".scalar(keys %netsplitservers) );
+    &DEBUG("nsC: netsplit: ".scalar(keys %netsplit) );
+
+    if ($count and !scalar keys %netsplit) {
+       &DEBUG("nsC: netsplit is hopefully gone. reinstating chanlimit check.");
+       &chanlimitCheck();
+    }
 }
 
 sub floodLoop {
@@ -357,7 +470,6 @@ sub floodLoop {
 
     if (@_) {
        &ScheduleThis(60, "floodLoop"); # minutes.
-       &ScheduleChecked("floodLoop");
        return if ($_[0] eq "2");
     }
 
@@ -365,7 +477,7 @@ sub floodLoop {
     my $interval       = &getChanConfDefault("floodCycle",60);
 
     foreach $who (keys %flood) {
-       foreach (keys %{$flood{$who}}) {
+       foreach (keys %{ $flood{$who} }) {
            if (!exists $flood{$who}{$_}) {
                &WARN("flood{$who}{$_} undefined?");
                next;
@@ -381,6 +493,12 @@ sub floodLoop {
 }
 
 sub seenFlush {
+    if (@_) {
+       my $interval = &getChanConfDefault("seenFlushInterval", 60);
+       &ScheduleThis($interval, "seenFlush");
+       return if ($_[0] eq "2");
+    }
+
     my %stats;
     my $nick;
     my $flushed        = 0;
@@ -388,15 +506,24 @@ sub seenFlush {
     $stats{'new'}      = 0;
     $stats{'old'}      = 0;
 
-    if (@_) {
-       my $interval = &getChanConfDefault("seenFlushInterval", 60);
-       &ScheduleThis($interval, "seenFlush");
-       &ScheduleChecked("seenFlush");
-       return if ($_[0] eq "2");
-    }
-
     if ($param{'DBType'} =~ /^mysql|pg|postgres/i) {
        foreach $nick (keys %seencache) {
+           my $retval = &dbReplace("seen", "nick", $nick, (
+###                    "nick" => $seencache{$nick}{'nick'},
+                       "time" => $seencache{$nick}{'time'},
+                       "host" => $seencache{$nick}{'host'},
+                       "channel" => $seencache{$nick}{'chan'},
+                       "message" => $seencache{$nick}{'msg'},
+           ) );
+           delete $seencache{$nick};
+           $flushed++;
+
+           next;
+
+           ###
+           ### old code.
+           ###
+
            my $exists = &dbGet("seen","nick", $nick, "nick");
 
            if (defined $exists and $exists) {
@@ -448,14 +575,13 @@ sub seenFlush {
 
     &status("Flushed $flushed seen entries.")          if ($flushed);
     &VERB(sprintf("  new seen: %03.01f%% (%d/%d)",
-       $stats{'new'}*100/$stats{'count_old'},
-       $stats{'new'}, $stats{'count_old'} ), 2)        if ($stats{'new'});
+       $stats{'new'}*100/($stats{'count_old'} || 1),
+       $stats{'new'}, ( $stats{'count_old'} || 1) ), 2) if ($stats{'new'});
     &VERB(sprintf("  now seen: %3.1f%% (%d/%d)",
-       $stats{'old'}*100/&countKeys("seen"),
+       $stats{'old'}*100 / ( &countKeys("seen") || 1),
        $stats{'old'}, &countKeys("seen") ), 2)         if ($stats{'old'});
 
     &WARN("scalar keys seenflush != 0!")       if (scalar keys %seenflush);
-
 }
 
 sub leakCheck {
@@ -463,45 +589,64 @@ sub leakCheck {
     my $count = 0;
 
     if (@_) {
-       &ScheduleThis(60, "leakCheck");
-       &ScheduleChecked("leakCheck");
+       &ScheduleThis(240, "leakCheck");
        return if ($_[0] eq "2");
     }
 
-    # flood.
+    # flood. this is dealt with in floodLoop()
     foreach $blah1 (keys %flood) {
-       foreach $blah2 (keys %{$flood{$blah1}}) {
-           $count += scalar(keys %{$flood{$blah1}{$blah2}});
+       foreach $blah2 (keys %{ $flood{$blah1} }) {
+           $count += scalar(keys %{ $flood{$blah1}{$blah2} });
        }
     }
-    &VERB("\%flood has $count total keys.",2);
+    &DEBUG("leak: hash flood has $count total keys.",2);
+
+    # floodjoin.
+    $count = 0;
+    foreach $blah1 (keys %floodjoin) {
+       foreach $blah2 (keys %{ $floodjoin{$blah1} }) {
+           $count += scalar(keys %{ $floodjoin{$blah1}{$blah2} });
+       }
+    }
+    &DEBUG("leak: hash floodjoin has $count total keys.",2);
+
+    # floodwarn.
+    $count = scalar(keys %floodwarn);
+    &DEBUG("leak: hash floodwarn has $count total keys.",2);
 
     my $chan;
     foreach $chan (grep /[A-Z]/, keys %channels) {
        &DEBUG("leak: chan => '$chan'.");
        my ($i,$j);
-       foreach $i (keys %{$channels{$chan}}) {
-           foreach (keys %{$channels{$chan}{$i}}) {
+       foreach $i (keys %{ $channels{$chan} }) {
+           foreach (keys %{ $channels{$chan}{$i} }) {
                &DEBUG("leak:   \$channels{$chan}{$i}{$_} ...");
            }
        }
     }
 
+    # chanstats
+    $count = scalar(keys %chanstats);
+    &DEBUG("leak: hash chanstats has $count total keys.",2);
+
+    # nuh.
     my $delete = 0;
     foreach (keys %nuh) {
        next if (&IsNickInAnyChan($_));
+       next if (exists $dcc{CHAT}{$_});
+
        delete $nuh{$_};
        $delete++;
     }
 
-    &DEBUG("$delete nuh{} items deleted; now have ".
+    &status("leak: $delete nuh{} items deleted; now have ".
                                scalar(keys %nuh) ) if ($delete);
 }
 
 sub ignoreCheck {
     if (@_) {
        &ScheduleThis(60, "ignoreCheck");
-       &ScheduleChecked("ignoreCheck");
+       return if ($_[0] eq "2");       # defer.
     }
 
     my $time   = time();
@@ -524,46 +669,64 @@ sub ignoreCheck {
 }
 
 sub ircCheck {
-    my @array = grep !/^_default$/, keys %chanconf;
-    my $iconf = scalar(@array);
-    my $inow  = scalar(keys %channels);
-    if ($iconf > 2 and $inow * 2 <= $iconf) {
-       &FIXME("ircCheck: current channels * 2 <= config channels. FIXME.");
+    if (@_) {
+       &ScheduleThis(60, "ircCheck");
+       return if ($_[0] eq "2");       # defer.
     }
 
-    # chanserv ops.
-    foreach ( &ChanConfList("chanServ_ops") ) {
-       next if (exists $channels{$chan}{'o'}{$ident});
-
-       &status("ChanServ ==> Requesting ops for $chan.");
-       &rawout("PRIVMSG ChanServ :OP $chan $ident");
+    my @x      = &getJoinChans();
+    my $iconf  = scalar( @x );
+    my $inow   = scalar( keys %channels );
+    if ($iconf > 2 and $inow * 2 <= $iconf) {
+       &FIXME("ircCheck: current channels * 2 <= config channels. FIXME.");
+       @joinchan       = @x;
+       &joinNextChan();
     }
 
-    if (!$conn->connected and time - $msgtime > 3600) {
-       &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
-       $msgtime = time();      # just in case.
-       &ircloop();
+    if (!$conn->connected or time() - $msgtime > 3600) {
+       # todo: shouldn't we use cache{connect} somewhere?
+       if (exists $cache{connect}) {
+           &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
+           $msgtime = time();  # just in case.
+           &ircloop();
+           delete $cache{connect};
+       } else {
+           &status("IRCTEST: possible lost in space; checking. ".
+               scalar(localtime) );
+           &msg($ident, "TEST");
+           $cache{connect} = time();
+       }
     }
 
     if ($ident !~ /^\Q$param{ircNick}\E$/) {
+       # this does not work unfortunately.
        &WARN("ircCheck: ident($ident) != param{ircNick}($param{IrcNick}).");
-       ### TODO: schedule check for own nick if taken?
-    }
 
-    &joinNextChan();
-       # if scalar @joinnext => join more channels
-       # else check for chanserv.
+       # this check is misleading... perhaps we should do a notify.
+       if (! &IsNickInAnyChan( $param{ircNick} ) ) {
+           &DEBUG("$param{ircNick} not in use... changing!");
+           &nick( $param{ircNick} );
+       } else {
+           &WARN("$param{ircNick} is still in use...");
+       }
+    }
 
     if (grep /^\s*$/, keys %channels) {
-       &WARN("we have a NULL chan in hash channels? removing!");
-       delete $channels{''};   # ???
-       &DEBUG("channels now:");
-       foreach (keys %channels) {
-           &status("  $_");
+       &WARN("ircCheck: we have a NULL chan in hash channels? removing!");
+       if (exists $channels{''}) {
+           &DEBUG("ircCheck: ok it existed!");
+       } else {
+           &DEBUG("ircCheck: this hsould never happen!");
        }
-       &DEBUG("channels END");
+
+       delete $channels{''};
     }
 
+    &DEBUG("ircstats...");
+    &DEBUG("  pubsleep: $pubsleep");
+    &DEBUG("  msgsleep: $msgsleep");
+    &DEBUG("  notsleep: $notsleep");
+
     ### USER FILE.
     if ($utime_userfile > $wtime_userfile and time() - $wtime_userfile > 3600) {
        &writeUserFile();
@@ -574,12 +737,13 @@ sub ircCheck {
        &writeChanFile();
        $wtime_chanfile = time();
     }
-
-    &ScheduleThis(240, "ircCheck") if (@_);
 }
 
 sub miscCheck {
-    &ScheduleThis(240, "miscCheck") if (@_);
+    if (@_) {
+       &ScheduleThis(240, "miscCheck");
+       return if ($_[0] eq "2");       # defer.
+    }
 
     # SHM check.
     my @ipcs;
@@ -599,34 +763,92 @@ sub miscCheck {
 
        my ($shmid, $size) = ($2,$5);
        next unless ($shmid != $shm and $size == 2000);
+       my $z   = &shmRead($shmid);
+       if ($z =~ /^(\d+): /) {
+           my $time    = $1;
+           next if (time() - $time < 60*60);
+
+       } else {
+#          &DEBUG("shm: $shmid is not ours or old blootbot => ($z)");
+#          next;
+       }
+
+       &status("SHM: nuking shmid $shmid");
+       CORE::system("/usr/bin/ipcrm shm $shmid >/dev/null");
+    }
+
+    # make backup of important files.
+    &mkBackup( $bot_misc_dir."/blootbot.chan", 60*60*24*3);
+    &mkBackup( $bot_misc_dir."/blootbot.users", 60*60*24*3);
+    &mkBackup( $bot_base_dir."/blootbot-news.txt", 60*60*24*1);
 
-###    &status("SHM: nuking shmid $shmid");
-###    system("/usr/bin/ipcrm shm $shmid >/dev/null");
+    # flush cache{lobotomy}
+    foreach (keys %{ $cache{lobotomy} }) {
+       next unless (time() - $cache{lobotomy}{$_} > 60*60);
+       delete $cache{lobotomy}{$_};
     }
 
     ### check modules if they've been modified. might be evil.
     &reloadAllModules();
 }
 
+sub miscCheck2 {
+    if (@_) {
+       &ScheduleThis(240, "miscCheck2");
+       return if ($_[0] eq "2");       # defer.
+    }
+
+    # debian check.
+    opendir(DEBIAN, "$bot_base_dir/debian");
+    foreach ( grep /gz$/, readdir(DEBIAN) ) {
+       my $exit = CORE::system("gzip -t $bot_base_dir/debian/$_");
+       next unless ($exit);
+
+       &status("debian: unlinking file => $_");
+       unlink "$bot_base_dir/debian/$_";
+    }
+    closedir DEBIAN;
+
+    # compress logs that should have been compressed.
+    # todo: use strftime?
+    my ($day,$month,$year) = (localtime(time()))[3,4,5];
+    my $date = sprintf("%04d%02d%02d",$year+1900,$month+1,$day);
+
+    opendir(DIR,"$bot_base_dir/log");
+    while (my $f = readdir(DIR)) {
+       next unless ( -f "$bot_base_dir/log/$f");
+       next if ($f =~ /gz|bz2/);
+       next unless ($f =~ /(\d{8})/);
+       next if ($date eq $1);
+
+       &compress("$bot_base_dir/log/$f");
+    }
+    closedir DIR;
+}
+
 sub shmFlush {
+    return if ($$ != $::bot_pid); # fork protection.
+
     if (@_) {
        &ScheduleThis(5, "shmFlush");
-       &ScheduleChecked("shmFlush");
        return if ($_[0] eq "2");
     }
 
+    my $time;
     my $shmmsg = &shmRead($shm);
     $shmmsg =~ s/\0//g;         # remove padded \0's.
-
-    return if ($$ != $::bot_pid); # fork protection.
+    if ($shmmsg =~ s/^(\d+): //) {
+       $time   = $1;
+    }
 
     foreach (split '\|\|', $shmmsg) {
+       next if (/^$/);
        &VERB("shm: Processing '$_'.",2);
 
        if (/^DCC SEND (\S+) (\S+)$/) {
            my ($nick,$file) = ($1,$2);
            if (exists $dcc{'SEND'}{$who}) {
-               &msg($nick,"DCC already active.");
+               &msg($nick, "DCC already active.");
            } else {
                &DEBUG("shm: dcc sending $2 to $1.");
                $conn->new_send($1,$2);
@@ -654,40 +876,44 @@ sub getNickInUse {
        return;
     }
 
-    &status("Trying to get my nick back.");
-    &nick( $param{'ircNick'} );
+    if (@_) {
+       &ScheduleThis(30, "getNickInUse");
+       return if ($_[0] eq "2");       # defer.
+    }
 
-    &ScheduleThis(30, "getNickInUse") if (@_);
+    &nick( $param{'ircNick'} );
 }
 
 sub uptimeLoop {
+    return unless &IsChanConf("uptime");
+
     if (@_) {
        &ScheduleThis(60, "uptimeLoop");
-       &ScheduleChecked("uptimeLoop");
+       return if ($_[0] eq "2");       # defer.
     }
 
     &uptimeWriteFile();
 }
 
 sub slashdotLoop {
-    &ScheduleThis(60, "slashdotLoop") if (@_);
-    &ScheduleChecked("slashdotLoop");
-    return if ($_[0] eq "2");
+
+    if (@_) {
+       &ScheduleThis(60, "slashdotLoop");
+       return if ($_[0] eq "2");
+    }
 
     my @chans = &ChanConfList("slashdotAnnounce");
     return unless (scalar @chans);
 
     &Forker("slashdot", sub {
-       my @data = &Slashdot::slashdotAnnounce();
+       my $line = &Slashdot::slashdotAnnounce();
+       return unless (defined $line);
 
        foreach (@chans) {
            next unless (&::validChan($_));
 
            &::status("sending slashdot update to $_.");
-           my $c = $_;
-           foreach (@data) {
-               &notice($c, "Slashdot: $_");
-           }
+           &notice($_, "Slashdot: $line");
        }
     } );
 }
@@ -695,7 +921,6 @@ sub slashdotLoop {
 sub freshmeatLoop {
     if (@_) {
        &ScheduleThis(60, "freshmeatLoop");
-       &ScheduleChecked("freshmeatLoop");
        return if ($_[0] eq "2");
     }
 
@@ -717,7 +942,6 @@ sub freshmeatLoop {
 sub kernelLoop {
     if (@_) {
        &ScheduleThis(240, "kernelLoop");
-       &ScheduleChecked("kernelLoop");
        return if ($_[0] eq "2");
     }
 
@@ -774,6 +998,11 @@ sub wingateCheck {
 
 ### TODO.
 sub wingateWriteFile {
+    if (@_) {
+       &ScheduleThis(60, "wingateWriteFile");
+       return if ($_[0] eq "2");       # defer.
+    }
+
     return unless (scalar @wingateCache);
 
     my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
@@ -798,42 +1027,72 @@ sub wingateWriteFile {
        print OUT "$_\n";
     }
     close OUT;
-
-    &ScheduleThis(60, "wingateWriteFile") if (@_);
 }
 
 sub factoidCheck {
-    my @list = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
-    my $stale = &getChanConfDefault("factoidDeleteDelay", 7)*60*60*24;
+    if (@_) {
+       &ScheduleThis(720, "factoidCheck");
+       return if ($_[0] eq "2");       # defer.
+    }
+
+    my @list   = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
+    my $stale  = &getChanConfDefault("factoidDeleteDelay", 30) *60*60*24;
+    my $time   = time();
 
     foreach (@list) {
        my $age = &getFactInfo($_, "modified_time");    
-       next unless (time() - $age > $stale);
+       &DEBUG("fC: _ => '$_'; age => $age");
+
+       if (!defined $age or $age !~ /^\d+$/) {
+           if (scalar @list > 50) {
+               if (!$cache{warnDel}) {
+                   &WARN("list is over 50 (".scalar(@list)."... giving it a miss.");
+                   $cache{warnDel} = 1;
+                   last;
+               }
+           }
+
+           &WARN("del factoid: old cruft (no time): $_");
+           &delFactoid($_);
+           next;
+       }
+
+       &DEBUG("del factoid: delta => ".($time - $age) );
+       next unless ($time - $age > $stale);
 
        my $fix = $_;
        $fix =~ s/ #DEL#$//g;
-       &VERB("safedel: Removing $fix for good.",2);
+       my $agestr = &Time2String($time - $age);
+       &DEBUG("safedel: Removing '$_' for good. [$agestr old]");
+
        &delFactoid($_);
     }
 
-    &ScheduleThis(1440, "factoidCheck") if (@_);
 }
 
 sub dccStatus {
-    my $time = strftime("%H:%M", localtime(time()) );
+    return unless (scalar keys %{ $dcc{CHAT} });
 
-    return unless (scalar keys %{ $DCC{CHAT} });
-
-    foreach (keys %channels) {
-       &DCCBroadcast("[$time] $_: $users members ($chops chops), $bans bans","+o");
+    if (@_) {
+       &ScheduleThis(10, "dccStatus");
+       return if ($_[0] eq "2");       # defer.
     }
 
-    &ScheduleThis(10, "dccStatus") if (@_);
-}
-
-sub schedulerSTUB {
+    my $time = strftime("%H:%M", localtime(time()) );
 
-    &ScheduleThis(TIME_IN_MINUTES, "FUNCTION") if (@_);
+    my $c;
+    foreach (keys %channels) {
+       my $c           = $_;
+       my $users       = keys %{ $channels{$c}{''} };
+       my $chops       = keys %{ $channels{$c}{o}  };
+       my $bans        = keys %{ $channels{$c}{b}  };
+
+       my $txt = "[$time] $c: $users members ($chops chops), $bans bans";
+       foreach (keys %{ $dcc{'CHAT'} }) {
+           next unless (exists $channels{$c}{''}{lc $_});
+           $conn->privmsg($dcc{'CHAT'}{$_}, $txt);
+       }
+    }
 }
 
 sub scheduleList {
@@ -870,7 +1129,11 @@ sub getChanConfDefault {
     my($what, $default, $chan) = @_;
 
     if (exists $param{$what}) {
-       &DEBUG("backward-compat: found param{$what} instead.");
+       if (!exists $cache{config}{$what}) {
+           &status("conf: backward-compat: found param{$what} ($param{$what}) instead.");
+           $cache{config}{$what} = 1;
+       }
+
        return $param{$what};
     }
 
@@ -878,10 +1141,37 @@ sub getChanConfDefault {
     if (defined $val) {
        return $val;
     }
+
     $param{$what}      = $default;
-    &status("gCCD: not configured; setting param{$what} = $default");
-    ### TODO: set some vars?
+    &status("conf: auto-setting param{$what} = $default");
+    $cache{config}{$what} = 1;
+
     return $default;
 }
 
+sub mkBackup {
+    my($file, $time)   = @_;
+    my $backup         = 0;
+
+    if (! -f $file) {
+       &WARN("mkB: file '$file' does not exist.");
+       return;
+    }
+
+    if ( -e "$file~" ) {
+       $backup++ if ((stat $file)[9] - (stat "$file~")[9] > $time);
+    } else {
+       $backup++;
+    }
+    return unless ($backup);
+
+    # should delta be time(file) - time(file~)?
+    my $delta  = time() - (stat "$file~")[9];
+    my $age    = &Time2String($delta);
+
+    ### TODO: do internal copying.
+    &status("Backup: $file ($age)");
+    CORE::system("/bin/cp $file $file~");
+}
+
 1;