#!/usr/bin/perl -w
# ----------------------------------------------------------------------- # 
# Copy the $SOURCEFILE to a new timestamped history file                  #
# and build the history index based on the timestamped                    #
# files we found. Delete files older then max history.                    #
#                                                                         #
# 20080110 support[at]frank4dd[dot]com                                    #
#                                                                         #
# we need Date::Calc, i.e. apt-get install libdate-calc-perl (Debian)     #
# ----------------------------------------------------------------------- #

use strict;                     # force to be strict
use Date::Calc  qw(:all);	# for date calculations

# Global Variables
use vars qw( $head_html $page_html $WEBDIR $SOURCEFILE $FILEPREFIX $INDEXFILE $fh @today );

# directory to create the index and history pages in
$WEBDIR = "/home/htdocs/admin/html/logwatch/fm4dd.com";

# source report to build history from
$SOURCEFILE = $WEBDIR."/logwatch.html";

# full path and name of the new index page
$INDEXFILE = $WEBDIR."/history-index.html";

# filename prefix for history pages
$FILEPREFIX = "logwatch-";

# ----------------------------------------------------------------------- #
# this function takes the formerly generated $SOURCEFILE to create a copy #
# with the name <$FILEPREFIX><yyyymmdd>.html for keeping a file history.  #
# ----------------------------------------------------------------------- #
sub timestamp_reportfile {
  my($DESTFILE) = "";

  # get todays date
  @today = Today();

  # add a leading zero (month)
  if($today[1] < 10) { $today[1] = "0".$today[1]; }

  # add a leading zero (day)
  if($today[2] < 10) { $today[2] = "0".$today[2]; }

  # create the full path to the file we want to create a hardlink for
  $DESTFILE .= $WEBDIR."/".$FILEPREFIX.$today[0].$today[1].$today[2].".html";

  # debug only
  #  print "New Name: $DESTFILE\n";

  # should we re-run the sript, we need to delete the former copy
  if(-r $DESTFILE) { unlink($DESTFILE); }

  # create the hardlink
  link($SOURCEFILE, $DESTFILE) || die "Cannot create link for $SOURCEFILE";
}

# ----------------------------------------------------------------------- #
# this function creates the standard html header + top description tables #
# ----------------------------------------------------------------------- #
sub create_htmlheader {
  my($pagetitle) = "Logwatch Report History";
  my($hostname)  = `hostname`;
  my($rundate)   = `/bin/date \"+%d.%m.%Y %H:%M\"`;
  $head_html     = << "EoText";
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR
/REC-html40/loose.dtd">
<html>
<head>
<title>$pagetitle</title>
<meta name="generator" content="Logwatch History">
<link rel=stylesheet type=text/css href=../style/style.css>
</head>
<body bgcolor="#006666" text="#FFFFFF">

<table border="0" cellpadding ="5" cellspacing="0" width="100%"><tr>
<td><a href=https://fm4dd.com>
<img src="../images/logo.gif" vspace=8 border=0></a></td>
<td><p align="center"><font face="Courier New,Courier"font color="#330000" font size=4><b>$pagetitle<br></b></font></p></td>
<td><img SRC="../images/logwatchlogo.gif" align="right"></td></tr>
</table>
<table BORDER=0 CELLSPACING=0 CELLPADDING=0 WIDTH="100%"><tr>
<td></td>
<td WIDTH="25%" bgcolor="000080" align="left"><font size="1" face="Arial" color="FFFFFF">
<b>&nbsp;Server: $hostname:443</b></font></td>
<td WIDTH="50%" BGCOLOR="#DCDCDC" align="center" nowrap><font face="Helvetica, Geneva, Arial" size=-2>&nbsp;<a href=history-index.html>[LogWatch: History]</a>&nbsp;<a href=http://fm4dd.com> [Domain: fm4dd.com]</a>&nbsp;<a href=https://fm4dd.com>[Back to Management]</a>&nbsp;</font></td>
<td WIDTH="25%" align="right" BGCOLOR="#004444" nowrap><font face="Arial" font size="1" color="#FFFFFF">&nbsp;Generated: $rundate JST&nbsp;</font></td>
</table>
<p><center>
EoText
}

# ----------------------------------------------------------------------- #
# this function creates the history index table and rest of the html body #
# ----------------------------------------------------------------------- #
sub create_htmlpage {
  my($histweeks) = 12;
  my($histdays) = $histweeks * 7;
  my(@weekdays) = ( '#', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Week' );
  my(@weekofyr);
  my(@daydate);
  my($weekstr);
  my($HISTFILE);
  my($EXPIREFILE);
  my(@filestat);
  my($time_now);

  $page_html = "<table WIDTH=\"700\">\n";
  $page_html .= "<tr>";

  # create the X-axis header columns
  my($j) = 0;
  while ( $j < 9 ) {
    $page_html .= "<th>";
    $page_html .= $weekdays[$j];
    $page_html .= "</th>";
    $j++;
  }

  $page_html .= "</tr>\n";

  # start creating the data rows
  my($i) = 0;
  while ( $i <= $histweeks ) {

    @today = Today();
    @weekofyr = Week_of_Year(Add_Delta_Days(@today, -($i*7)));
    $weekstr = $weekofyr[1]."/".($weekofyr[0]);

    $page_html .= "<tr>";

    # Y-axis startheader shows the history number
    $page_html .= "<th>";
    $page_html .= $i;
    $page_html .= "</th>";

    my($j) = 0;
    while ( $j < 7 ) {
      @daydate = Add_Delta_Days(Monday_of_Week(@weekofyr),$j);
      if($daydate[2] < 10) { $daydate[2] = "0".$daydate[2]; }
      if($daydate[1] < 10) { $daydate[1] = "0".$daydate[1]; }
      $HISTFILE = $FILEPREFIX.$daydate[0].$daydate[1].$daydate[2].".html";

      $page_html .= "<td class=\"date\">";
      if(-r $WEBDIR."/".$HISTFILE) {
        $page_html .= "<a href=\"".$HISTFILE."\">";
        $page_html .= $daydate[2].".".$daydate[1].".".$daydate[0];
        $page_html .= "</a>";
      }
      else {
        $page_html .= $daydate[2].".".$daydate[1].".".$daydate[0];
      }
      $page_html .= "</td>";
      $j++;
    }

    # Y-axis endheader shows the week of year
    $page_html .= "<th>";
    $page_html .= $weekstr;
    $page_html .= "</th>";

    $page_html .= "</tr>\n";
    $i++;
  }

  # we expire the oldest file in history starting from here:
  $page_html .= "<tr>\n";
  $page_html .= "<td class=\"date\" colspan=9>\n";

  # expire the file older then in the current view
  @daydate = Add_Delta_Days(@today, -$histdays);
  if($daydate[2] < 10) { $daydate[2] = "0".$daydate[2]; }
  if($daydate[1] < 10) { $daydate[1] = "0".$daydate[1]; }
  $EXPIREFILE = $FILEPREFIX.$daydate[0].$daydate[1].$daydate[2].".html";
  $page_html .= "file expired: ".$EXPIREFILE;

  # delete the expired file and report about it
  if(-r $EXPIREFILE) {
    unlink($EXPIREFILE);
    $page_html .= "<br>... file successfully deleted.";
  }

  # close the field, row and table
  $page_html .= "</td>\n";
  $page_html .= "</tr>\n";
  $page_html .= "</table>";
}

# ----------------------------------------------------------------------- #
# main(), run the functions in order and write the history index file     #
# ----------------------------------------------------------------------- #
timestamp_reportfile();
create_htmlheader();
create_htmlpage();

# For debug, enable terminal output
# print $head_html;
# print $page_html;

# write the index page
open( OUT, ">$INDEXFILE" )
      or die ("$0: can't open $INDEXFILE for writing: $!\n");
$fh = *OUT;
print $fh $head_html;
print $fh $page_html;
print $fh "</body></html>";
close( OUT );
# ----------------------------------------------------------------------- #
# end of main(), end of program, end of file                              #
# ----------------------------------------------------------------------- #
