#!/usr/bin/perl

use strict;
use File::stat;


sub GenerateRepomdXml {
    my ($patches_directory) = @_;
    opendir(PDIR,"$patches_directory");
    my @all_patches = grep {/\.xml(\.gz)?$/} readdir(PDIR);
    closedir(PDIR);
    open (NEWDIR,">$patches_directory/repomd.xml");
    print NEWDIR "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    print NEWDIR "<repomd xmlns=\"http://linux.duke.edu/metadata/repo\">\n";
    my $pdirname = $patches_directory;
    $pdirname =~ s/^.*\///;
    for (@all_patches) {
        next if (/^patch-/);
        next if (/^repomd/);
        my ($checksum,$dummy) = split('\s+',`sha1sum "$patches_directory/$_"`);
        my $o_checksum = $checksum;
        if ( /\.gz/ ) {
            ($o_checksum,my $dummy) = split('\s+',`gzip -dc "$patches_directory/$_" | sha1sum`);
        }
        my $timestamp = stat("$patches_directory/$_")->mtime;
        my $filename = $_;
        $_ =~ s/.xml(\.gz)?$//;
        print NEWDIR "  <data type=\"$_\">\n";
        print NEWDIR "    <location href=\"$pdirname/$filename\"/>\n";
        print NEWDIR "    <checksum type=\"sha\">$checksum</checksum>\n";
        print NEWDIR "    <timestamp>$timestamp</timestamp>\n";
        print NEWDIR "    <open-checksum type=\"sha\">$o_checksum</open-checksum>\n";
        print NEWDIR "  </data>\n";
    }
    print NEWDIR "</repomd>\n";
    close ( NEWDIR );
}

my $rsyncable = "";

my $arg = shift @ARGV;
my $tmpdir = `mktemp -d /tmp/mk_listings.XXXXXX`;
chomp ($tmpdir);
if ( $arg ) {
    die("need an argument") unless ( -d $arg );
}

if ( $arg !~ /^\// ) {
    my $pwd = `pwd`;
    chomp ($pwd);
    $arg = "$pwd/$arg";
}

system ("touch", "$tmpdir/fff");
system (`gzip --rsyncable "$tmpdir/fff" >/dev/null 2>/dev/null`);
if ( -f "$tmpdir/fff.gz" ) {
    $rsyncable = "--rsyncable";
}
system ("rm", "-f", "$tmpdir/fff", "$tmpdir/fff.gz");

if ( $rsyncable ) {
  my @GZIPPED = glob("$arg/*.gz");
  for (@GZIPPED) {
    system ("gunzip", "-f", $_);
    $_ =~ s/.gz$//;
    system ("gzip", "-9", $rsyncable, $_);
  }
  my $has_sign = "";
  $has_sign = "1" if ( -f "$arg/repomd.xml.asc" );
  system ("cp", "-a", "$arg/repomd.xml.key", $tmpdir) if ( -f "$arg/repomd.xml.key" );
  if ( -f "$arg/repomd.xml" ) {
    unlink "$arg/repomd.xml";
    GenerateRepomdXml($arg);
  }
  if ( $has_sign ) {
    unlink "$arg/repomd.xml.asc";
    system ("sign", "-d", "$arg/repomd.xml");
  }
  if ( -f "$tmpdir/repomd.xml.key" ) {
    system ("cp", "-a", "$tmpdir/repomd.xml.key", $arg);
  }
  if ( -f "$arg/MD5SUMS" ) {
    system ("create_md5sums", $arg);
  }
}

system("rm", "-r", "-f", $tmpdir);

