#!/usr/bin/perl
#
# Quick and dirty script to produce a template with all the trusted CAs.
#
# Must be run from the directory where are the CA rpms

use strict;

# Obsolete CAs are often still distributed for some time. 
# Include them commented out.
# Value has no importance, can be set to the version where it has been obsoleted
my %obsolete_cas = ( "lcg_ca_FNAL_KCA" => "1.7-1",
                   );


sub usage () {
  print "Usage:\tcreate_template [RPM_directory]\n";
  exit 1;
}

if ( @ARGV > 1 ) {
  usage();
}

my $ca_rpms_dir = ".";

for my $option (@ARGV) {
 if ( $option eq '-h' ) {
   usage();
 } else {
   $ca_rpms_dir = $option;
 };  
}

opendir (CADIR, $ca_rpms_dir) || die 'Unable to get current directory listing';
my @ca_rpms = grep /\.rpm$/, readdir(CADIR);
close CADIR;

my $first = 1;

for my $rpm (@ca_rpms) {
  if ( $first ) {
    $first = 0;
    print "unique template common/security/cas;\n\n";
  }

  #print STDERR "Processing $rpm\n";
  my ($name, $version, $release, $arch) = ($rpm =~ m/^((?:\w+\-*)+)\-([\d\.]+)\-(\d)\.(\w+)\.rpm$/);
  unless ( $name ) {
    print STDERR "Skipping $rpm (doesn't match a valid CA rpm name)\n";
  }
  my $prefix = '';
  if ( exists($obsolete_cas{$name}) ) {
    $prefix = '#';
  }
  print $prefix."'/software/packages' = pkg_repl('$1', '$2-$3', '$4');\n";

}
