#!/bin/perl -w

#############################################################
#                                                           #
#  This example outputs a document with the list of module  #
#  in freshmeat.xml that are installed on the system.       #
#  A 'used' element is created for each module the version  #
#  installed if the VERSION variable is set in the module.  # 
#  An attribute update is also added to the module element  #
#  if the stable version of the module is higher than the   #
#  installed version                                        #
#                                                           #
#   Note: this example shows that I messed up the version   #
#          system by using 1.9 instead od 1.09 ;--(         #
#                                                           #
#############################################################

use strict;
use XML::Twig;


my $twig= new XML::Twig(               # create the twig
              TwigHandlers => 
                { module => \&module,  # module handler
                }  
                        );                                                   

if( my $file= $ARGV[0]) { $twig->parsefile( $file); }   # process the twig
else                    { $twig->parse( \*STDIN);   }
$twig->flush;                                           # don't forget this one
print "\n";


sub module
  { my( $twig, $module)= @_; 
    my $name= $module->field( 'name');                   # get the module name
    if( eval "require $name")                            # require it
      { no strict 'refs';                                # so next line is OK
        my $version=     ${$name."::VERSION"}            # get the version
                     || 'none';
        my $used= new XML::Twig::Elt( 'used', $version); # create the element
        $used->paste( 'last_child', $module);            # paste it

        my $stable= $module->field( 'stable');           # get stable version
        unless( ($version eq 'none') || ($stable eq 'none'))
          { if( $stable > $version) 
              { $module->set_att( update => "yes"); }    # add update att
          }
         $twig->flush;                                   # print the twig
         print "\n";
      }
    else
      { $module->delete }

  }

