#!/usr/bin/perl 

# Copyright (c) 2004 by Charles A. Loomis, Jr. and Le Centre National de
# la Recherche Scientifique (CNRS).  All rights reserved.

# The software was distributed with and is covered by the European
# DataGrid License.  A copy of this license can be found in the included
# LICENSE file.  This license can also be obtained from
# http://www.eu-datagrid.org/license.

use strict;
use Cwd;
use File::Path;
use Getopt::Long;

# Setup of the options.
my %options = ();
&GetOptions(\%options, "help", "saxon=s");

# Print help if necessary. 
if ($options{help}) {
    usage();
    exit;
}

# Check that the saxon jar file exists. 
my $saxon = "./saxon8.jar";
if (!defined($options{saxon})) {
    $saxon = $options{saxon};
}
if (! -e $saxon) {
    print "Saxon jar file ($saxon) doesn't exist.\n";
    usage();
    exit(1);
}

# Check that an input file was given. 
my $input = shift;
if (!defined($input)) {
    print "Must supply input LLD.\n";
    usage();
    exit(1);
}

# Transform the LLD file to an rpm list.  MUST decode the URLs which
# are returned.  (They are encoded by quattor.)
my $cmd = "export CLASSPATH=$saxon; java net.sf.saxon.Transform $input xmldb2pkgs.xsl";
my $output = `$cmd`;
$output =~ s!(_[0-9a-f]{2})!sprintf("%c",hex($1))!meg;
$output =~ s!(\n)!' '!meg;

# Create a temporary database. 
my $rpmdb = "/tmp/test/rpmdb/$$/";
die "$rpmdb already exists\n" if (-e $rpmdb);
mkpath($rpmdb);
    
# Initialize the database.
print "Initializing rpm database ($rpmdb)...\n";
`rpm --initdb --dbpath $rpmdb`;

# Try installing all of the rpms. 
print "Installing rpms...\n";
`rpm --install --test --justdb --ignoresize --dbpath $rpmdb $output`;

# Remove the database. 
rmtree($rpmdb);

exit;

sub usage {

    print << "EOF"

This script takes an LLD file generated by the CDB component of
quattor, extracts an rpm list by transforming the XML, and runs a fake
installation of those rpms to ensure that the list works correctly. 

Usage:

rpmcheck.pl [--saxon=full_path] <LLD file>

Giving no arguments prints this help message.  The saxon jar file
(v7+) must be available.  If the path is not given, then the current
directory is assumed. 

EOF
; 

}
