#!/usr/bin/perl -w
#
# addnews.pl document_uri
#
# Agrega una noticia a la estructura del WebCIE.
#
# Version 0.0, 010319
#       Esperamos no cuatrapear los archivos actuales :-)
#       Me parece que las cosas serían mucho más fáciles usando
#       siempre XPath...

use XML::XPath;
use XML::XPath::XMLParser;
use File::stat;

my $_DEBUG_=1;
my $DOCUMENT_ROOT="/home/httpd/webcie";

print "BEGINING..." if $_DEBUG_;

die "Need document_uri" unless $#ARGV==0;
my $document = $ARGV[0];
die "document_uri Must be absolute" if $document =~ m:\.\./:;
$filename = $DOCUMENT_ROOT . $document;
die "Can't find $filename" unless -e $filename;
my $sb = stat($filename);

print "Trying to parse $filename\n" if $_DEBUG_;
my $xp = XML::XPath->new(filename => $filename);
die "$filename is not a valid XML file" unless $xp;

my $title = $xp->find('/news/title');
my $abstract = $xp->find('/news/abstract');
my $author = $xp->find('/news/author/text()');
my $email = $xp->find('/news/author/@e-mail');
my $date = localtime($sb->mtime);

$menufile = $filename;
$menufile =~ s:/[^/]+\.xml$:/menu.xml:;
print "Trying to parse $menufile\n" if $_DEBUG_;
$xp = XML::XPath->new(filename => $menufile);
die "Can't open $menufile" unless $xp;
my $nodeset = $xp->find('/menu/parent|/menu/item');
foreach my $node ($nodeset->get_nodelist) {
  my $sectionpath = $xp->find('./@href', $node);
  push @backpath, $sectionpath;
}

while(my $sectionpath=pop(@backpath)) {
  print "Working on $sectionpath\n" if $_DEBUG_;
  $path="$DOCUMENT_ROOT/$sectionpath";
  $path=~s://:/:; $path=~s:/$::;
  print "Trying to parse news.xml\n" if $_DEBUG_;
  $xp = XML::XPath->new(filename => "$path/news.xml");
  die "Invalid news.xml on $path" unless $xp;
  my $lastnews = $xp->findnodes_as_string('/news/item[position()<9]');
  print "Trying to rename $path/news.xml\n" if $_DEBUG_;
  rename "$path/news.xml", "$path/news.bak" or die "Can't rename news.xml on $path";
  print "Trying to open $path/news.xml\n" if $_DEBUG_;
  open NEWS, ">$path/news.xml" or die "Can't create news.xml on $path";

  print NEWS << "-EOF-"
<?xml version="1.0"?>
<news version="0.0">

  <item href="$document">
    <title>$title</title>
    <author e-mail="$email">$author</author>
    <date format="ctime">$date</date>
    <abstract>$abstract</abstract>
  </item>
  $lastnews
</news>
-EOF-
;
  close NEWS or die "Can't close news.xml on $path";
}

print "FINISHED\n" if $_DEBUG_;
