#!/usr/bin/perl

use XML::XPath;
use XML::XPath::XMLParser;


my %distmap = (
  "openstack-octavia-amphora-image.SLE_12_SP4.config.xml" => "%if 0%{?suse_version} == 1315",
);

sub map_kiwiname_to_suseversion($){
  my $kiwi = shift;
  my $ret = "ERROR: please add $kiwi to $0";

  $ret = "$distmap{$kiwi}" if (exists $distmap{$kiwi});

  return $ret;
}

my $xp = XML::XPath->new();
my $skip=0;

open FH, '<', 'openstack-octavia-amphora-image.spec' or die "Error: could not open openstack-octavia-amphora-image.spec: ".$?;
my @kiwiconfigs = glob("*.config.xml");

while (<FH>) {
  if ($_ =~ /^# END: generated BuildRequires/) {
    $skip = 0;

    foreach my $kiwi (@kiwiconfigs) {
      print map_kiwiname_to_suseversion($kiwi)."\n";
      print "# START: packages for $kiwi\n";

      my $xp = XML::XPath->new( filename => $kiwi, parser => $xp->get_parser );
      my $nodeset = $xp->find('/image/packages[@type!="delete"]/package[@name]');

      # we'll create a hash that list packages for each architecture
      my %packages;

      foreach my $pkg ($nodeset->get_nodelist) {
        my $arch = $pkg->getAttribute('arch') || 'common';
        @packages{$arch} = [] unless length(@packages{$arch});
        push(@{$packages{$arch}}, $pkg->getAttribute('name') || "brokenXML");
      }

      # first list BuildRequires common to all architectures, and then specific
      # to each architecture
      foreach my $name (sort(@{$packages{'common'}})) {
        print "BuildRequires:  ".($name)."\n";
      }

      foreach my $arch (sort(keys(%packages))) {
          next if $arch eq 'common';
          print "%ifarch ".($arch)."\n";
          foreach my $name (sort(@{$packages{$arch}})) {
            print "BuildRequires:  ".($name)."\n";
          }
        print "%endif\n";
      }

      # We excluded the deleted packages, so we need to add some
      # missing dependencies
      print "BuildRequires:  plymouth-branding\n";
      
      print "# END: packages for $kiwi\n";
      print "%endif\n";
    }
  }

  print $_ unless $skip;
  $skip = 1 if $_ =~ /^# START: generated BuildRequires/;
}

close FH;
