#!/usr/bin/perl
########################################################################
# Perl CGI Script: since-rdf.cgi
#
# This script was created to access the file lists via a nice
# easy-on-the-bandwidth HTTP method instead of the current FTP
# connections.  It was done to scratch an itch of wanting to know
# which of the many RPM files in the cooker (or contrib or whatever)
# had been updated since I'd last looked so I could pick and choose
# any that seemed interesting.
#
# This script is intended to run on the server-side and returns a
# well-ordered RDF 1.0 list of files which have changed since the last
# request.  The script can be plunked into the same directory as the
# files, but typically will be set somewhere else.
#
# OUTPUT:
# 
# Given the datestamp of the last time you asked for updates, you get an
# html table listing only those files newer than your datestamp:
# 
#     Expires: Fri, 25 Oct 2002 17:57:34 GMT
#     Date: Fri, 25 Oct 2002 17:57:24 GMT
#     Etag: "1035483508" 
#     Last-modified: Thu, 24 Oct 2002 18:18:28 GMT 
#     Content-Type: text/xml; charset=ISO-8859-1
#
#     <?xml version="1.0" encoding="UTF-8"?>
#     (RDF 1.0 giving file names, authors, desc, &c) ...
# 
# Etag and Last-modified are set to the timestamp of the youngest file.
#
# If there have been no updates, you get a nice bandwidth-friendly 304:
# 
#     Status: 304 Not Modified 
#     Etag: "1035487019" 
#     Last-modified: Thu, 24 Oct 2002 19:16:59 GMT 
#     Content-Type: text/html; charset=ISO-8859-1
# 
# USEAGE:
#
# We can poll this page as often as we like without bankrupting the
# server with bandwidth overdraft charges ;) a needless request is
# only a few hundred bytes, and an update reply only includes the files
# added since you last called.  If you need a resend, no problem, you
# just roll back your stored last Etag timestamp and try again!
# 
# Intelligent client software would retain the Etag /or/ the
# Last-modified and use those in the header of the next request,
# or use the Etag timestamp as the GET path-info.  For a dumb solution,
# you'd touch some local file each time you get a result, and use that
# timestamp as the path-info value on the next call.
#
# A simple shell script could just dump the date to a timestamp file
# when it's done and then call this script with lynx:
#
# lynx -source http://host/since-rdf.cgi/`cat .last_access` \
#       > updates.rdf && date +"%s" > .last_access
#
# there's probably even a way to specify the If-modified-header in
# lynx or wget -- I'm just too lazy to look it up.
# 
# BUGS: 
#
# - Only has a resolution of one second -- if you make a request at
#   the top of the second and a file that is not in your list arrives
#   before the rollover happens, the next request won't include that
#   file; since the file would need to be pretty tiny to be closed
#   within the partial second, here's hoping it's not important -- if
#   this becomes an issue, then the list could be set to duplicate the
#   end/start documents.
#
# - the taxonomy link is a joke; if there is a better place to direct
#   these then please, please recommend one
#
# - Escaping of invalid strings in the XML file is naive -- who knows
#   what abominations lurk in the hearts of RPM authors
#
# NO WARRANTEE EXPRESSED OR IMPLIED including the warrantee that this
# is either efficient or even the best way to do this task; your mileage
# may vary, caveat emptor, offer void where prohibited by law.
#
# REQUIRES: HTTP::Date XML:RSS RPM::Header and CGI.pm
#
# Created: Thu Oct 24 15:30:05 EDT 2002
#
# Author:  Gary Lawrence Murphy <garym@teledyn.com>
# License: GNU General Public License
# Copyright:  2002 TeleDynamics Communications Inc (www.teledyn.com)
# Version: 0.1.2
########################################################################

use CGI qw/:standard/;
use XML::RSS;
use HTTP::Date;

use RPM::Header;

$n = "\n";
$query = new CGI;
$day = 3600 * 24.0;

$debug = 0;
print header if $debug;

########################################################################
# CONFIGURATION
#
# you need to set the file-pattern to include, the host site of the
# channel, base URL and real filepage for the files (they need not be
# the document root
########################################################################

$filter = '.*\.rpm$';
$uribase = '/pub/cooker/Mandrake/RPMS';
$filebase = '/mnt/disk2/pub/cooker/Mandrake/RPMS';

########################################################################
# set the dublin core and channel metadata
########################################################################

$title = 'Mandrake Cooker Updates';
$channeldesc = 'this channel returns a list of file latest updates since some user-specified cut-off date; use Etag or GET /pathinfo with a unix time long value or use If-Modified-Since with an RFC-822 date to specify the cutoff (default is 24hrs)';
$subject = 'Mandrake Linux';
$creator = $query->http('SERVER_ADMIN');
$publisher = $creator;

$lang = 'en-us';

########################################################################
# probable end of configuration section
########################################################################
$copyright = 'Copyright 2002 Teledynamics (teledyn.com)';

$site = "http://". $query->server_name() . ":" . $query->server_port();

$pubdate = `date  --rfc-822`;
chop $pubdate;

########################################################################
# set up the channel metadata
########################################################################

my $rss = new XML::RSS (version => '1.0');
$rss->channel(
      title        => $title,
      link         => $site,
      description  => $channeldesc,
      dc => {
            date       => $pubdate,
            subject    => $subject,
            creator    => $creator,
            publisher  => $publisher,
            rights     => $copyright,
            language   => $lang,
      },
      syn => {
            updatePeriod     => "hourly",
            updateFrequency  => "1",
            updateBase       => "1901-01-01T00:00+00:00",
      },
      taxo => [
            'http://dmoz.org/Computers/Internet',
            'http://dmoz.org/Computers/PC'
      ]
    );

########################################################################
# get the cut-off date as a unix time value path-info or as a req header
########################################################################

if (path_info()) {
    $since = substr(path_info(),1); # time() long int
} elsif (http('If-Modified-Since')) {
    $since = str2time(http('If-Modified-Since')); # normal date string
} elsif (http('Etag')) {
    $since = http('Etag'); # unix time as a string
} else {
    $since = (time() - $day); # default 24hrs
}

print $n . p("searching for $filter in $filebase since $since") if $debug;

########################################################################
# count up the files newer than the cutoff date
########################################################################

opendir(DIR, $filebase);
    @files = grep {!/^\./} readdir(DIR);
    my $count = @files;
    print $n . p("found $count files") if $debug;
    if (defined($filter)) {
        @files = grep {/$filter/} @files;
    }
    @files = sort  by_filedate @files;
    $count = @files;
    print $n . p("sorted $count files") if $debug;
closedir(DIR);

########################################################################
# record the newest file's timestamp or use now if no files
########################################################################

my $d;
my @newer;
my $newest = time();
if (@files) {
  $newest = time() - ((-M "$filebase/$files[0]") * $day);
  print $n . p("Latest update is $files[0] at " 
         . time2str($newest) . " ($newest)") if $debug;

}

########################################################################
# add the qualifying items to the RSS object
########################################################################
my $pkgcount = 0;
foreach $d (@files)
  {
    my $age = time() - ((-M "$filebase/$d") * $day);

    if (-f "$filebase/$d" && $age > $since) {

      $pkgcount++;
      print $n . b("$d - " . time2str($age)) if $debug;

      add_item( $d, $age );

    } else { 
      print $n . em("$d is last file at $age") if $debug;
      last; 
    } # short circuit search down sorted list
  }

print $n . p("found $pkgcount newer files") if $debug;

########################################################################
# if there are no newer files, return a 304 Not Modified header
# otherwise return the list of files; give the most recent date
# as the new cutoff date.
########################################################################

if (!$pkgcount) { # return no change header

print $n . p("no files $since days old.") if $debug;

print header( -content_type => 'text/xml',
              -last_modified => time2str($newest), 
              -expires => '+1s',
              -etag => "\"$newest\"",
              -status=>'304 Not Modified' );

} else {

  print header( -content_type => 'text/xml',
                -last_modified => time2str($newest), 
                -etag => "\"$newest\"",
                -expires => '+10s');

  print $rss->as_string;
}

########################################################################
# sort into date-ordered lists so we can short circuit the hunt
########################################################################
sub by_filedate{
    my $result;
    if (length($a) == 0 || length($b) == 0){
        $result=0;
    } else {
    $result= (-M "$filebase/$a") <=> (-M "$filebase/$b");
    }
    return $result;
}

########################################################################
# target specific methods (eventually class/subclass methods)
########################################################################

# RPM method
sub dump_item {
  my $rpm = "$filebase/" . shift;
  return unless $debug;

  tie %hdr, "RPM::Header", $rpm or return;

  for (sort keys %hdr)
    {
      next if /GIF/;
      print $n . '<table>' if $debug;
      print $n . Tr( td( { -valign => "top" }, $_ ) . td( li($hdr{$_}))) if $debug;
      print $n . '</table>' if $debug;
    }
}

sub add_item {
  my ($d, $age) = @_;
#  dump_item($d);
  my %hdr;
  tie %hdr, "RPM::Header", "$filebase/$d" 
    or do {
      print "<b>bad RPM</b>" if debug;
    };

  print $n . "$d :<blockquote>" .  $hdr{'DESCRIPTION'}
  . '</blockquote>' if $debug;

  my @taxo = ( 'http://dmoz.org/Computers/Software/' . $hdr{'GROUP'} );
  unshift @taxo, $hdr{'URL'} if $hdr{'URL'};

  $rss->add_item(
                 title       => escapeHTML("$d"),
                 link        => "$uribase/$d",
                 description => escapeHTML($hdr{'DESCRIPTION'})
                 || 'no description available',
                 dc => {
                        date       => time2str($hdf{'BUILDTIME'})
                        || $age,
                        publisher  => escapeHTML($hdr{'DISTRIBUTION'}),
                        rights     => escapeHTML($hdr{'COPYRIGHT'}),
                        subject  => escapeHTML($hdr{'GROUP'}),
                        type => $hdr{'ARCH'},
                        creator  => escapeHTML($hdr{'PACKAGER'}),
                        source  => $hdr{'SOURCERPM'}
                       },
                 taxo => [ @taxo ]

                ) or die 'RPM error';
}

1;

########################################################################
# 2002 by TeleDynamics Communications Inc - info@teledyn.com
