#!/usr/local/bin/perl
#WHMADDON:logscheduler:Schedule Statistics Log Times
#
##########################################################

BEGIN {
  push(@INC,"/usr/local/cpanel");
  push(@INC,"/usr/local/cpanel/whostmgr/docroot/cgi"); 
}

use whmlib;

require "parseform.pl";
my %FORM = parseform();

########################################################
# Dont allow Resellers to view logschedule
########################################################
if (!$ACL{all}) {
        print "logschedule is installed and running!\n";
        exit();
}
		


########################################################
if ($FORM{'cgiaction'} eq "submit") {
   print "Content-Type: text/html\n\n";
   handleForm();
}
else {
   printForm();
}

########################################################
#
########################################################
sub printForm {
    my %stat_conf = load_Config("/etc/stats.conf");
    my %cpan_conf = load_Config("/var/cpanel/cpanel.config");
    my @hours = split(/,/,$stat_conf{'BLACKHOURS'});
    my $cycle = (defined($cpan_conf{'cycle'})) ? $cpan_conf{'cycle'}:0;
    print "Content-Type: text/html\n\n";
    defheader("Statistics Log Schedule");
    print "<fieldset><legend>Schedule Blackout Hours</legend>";
    print "Check the hours that you would like log analysis <u><b>NOT</b></u> to be performed.<br/>";
    print "<i>Note: Keep in mind that if there isn't enough time allocated to running ";
    print "log analysis, your logs may never fully be completely analyzed.</i>\n";
    print "<form action='./addon_logscheduler.cgi'>\n";
    print "<input type=hidden name=cgiaction value=submit>\n";
    print "<table align=center width=80% cellspacing=0 cellpadding=0 border=1>\n";
    my $bg = "2";
    for my $i (0..5) {
         print "<tr class='tdshade$bg'>";
         for my $j (0..3) {
            my $ni = ($j * 6) + $i;
            print "<td width=20><input type=checkbox name='$ni' value='yes'";
            if (grep(/^${ni}$/,@hours)) { print " CHECKED"; }
            print "></td><td>";
            if ($ni < 10) { print "0"; }
            print "$ni:00</td>";
         }
			print "</tr>";
         if ($bg eq "2") { $bg = "1"; }
         else { $bg = "2"; }
    }
    print "</table>&nbsp;<br/>";
    print "<table align=center width=100% cellspacing=0 cellpadding=0 border=0>";
    print "<tr><td width=50>Log Cycle:</td><td width=60><input class='submit' size=5 type=text name='cycle' value='${cycle}'></td>";
    print "<td><i>Note: The log cycle is the number of days between log runs.(ie. 1 would run the logs everyday. 2 would run the logs once every other day. 0.5 would run the logs twice a day)</i></td>";
    print "</tr></table>";
    print "&nbsp;<br/><input class='submit' type=submit value='Submit'>";
    print "</form>";
    print "</fieldset>";
}

####################################################
#
####################################################
sub handleForm {
   my @hours = ();
   my %stat_conf = load_Config("/etc/stats.conf");
   my %cpan_conf = load_Config("/var/cpanel/cpanel.config");

   for my $i (0..23) {
       if (defined($FORM{$i}) && lc($FORM{$i}) eq "yes") {
          push @hours, $i;
       }
   }
   my $hours_str = join(",",@hours);
   if (defined($FORM{'cycle'}) && $FORM{'cycle'} =~ m/^\d+$/) {
      $cpan_conf{'cycle'} = $FORM{'cycle'};
   }
   $stat_conf{'BLACKHOURS'} = $hours_str;
   # Write hours out to file.
   flushConfig(\%stat_conf,"/etc/stats.conf");
   # Write cycle out to file.
   flushConfig(\%cpan_conf,"/var/cpanel/cpanel.config");

   defheader("Statistics Log Schedule");
   if ($#hours >= 15) { handleBlackout($#hours + 1); }
   print "<fieldset><legend>Log Schedule Results</legend>";   
   restartCpanelLogd();
   print "</fieldset>";
   print "[ <a href='./addon_logscheduler.cgi'>Go Back</a> ]";
}

##############################################################################
#
##############################################################################
sub handleBlackout {
   my ($hours) = @_;
   print "<fieldset><legend>Warning</legend>\n";
   print "<b>You have selected ${hours} hours for logs <u><b>NOT</b></u> to be run. ";
   print "This may not leave enough time for stats to be processed. ";
   print "If you would like to modify these settings, please use your ";
   print "back button, and reselect the hours you would like stats to not be processed.";
   print "</b></fieldset><br/>\n";
}

##############################################################################
#   load_Config - Parses the given file which should be hold key/value pairs
#     one pair per line of the format, Key=Value
#     The returned hash is a representation of that file.
##############################################################################
sub load_Config {
   my ($file) = @_;
   if (! -e $file) { return undef; }

   my %conf;
   open(CONF,"<",$file) or return undef;
   my @dconf = <CONF>;
   close(CONF);
   @dconf = map { chomp; $_; } @dconf;
   foreach my $line (@dconf) {
      my ($var,$val) = split(/=/,$line);
      $conf{$var} = $val;
   }
   return %conf;
}

##############################################################################
#
##############################################################################
sub restartCpanelLogd {
   system("/scripts/ckillall","-9","cpanellogd");
   system("/usr/local/cpanel/cpanellogd >/dev/null");
   print "<b>cpanellogd Restarted.</b>";
}
                                                                                                                                                             
##############################################################################
#
##############################################################################
sub flushConfig {
   my ($conf,$filename) = @_;

   my @aconf = map("$_=$$conf{$_}",sort keys %$conf);
   open(CONF,">",$filename) or return 0;
   flock(CONF,2); # Ask for an exclusive lock.. Though it's only a suggestion, why not..?
   print CONF join("\n",@aconf);
   flock(CONF,8); # Release the lock..
   close(CONF);
   return 1;
}

