#!/usr/bin/perl

BEGIN {
  unshift @INC, '/usr/lib/build';
}

use strict;
use warnings;

use Build;

# Used by the 20-files-present-and-referenced script to extract the
# sources, patches, and icons from a spec file.
# Input: spec file, sources file
# The extracted sources, patches, and icons are written/appended to the
# sources file (one single line; each entry is separated by a whitespace).

sub parse {
  my ($fn) = @_;
  # use noarch, because the spec shouldn't contain arch specific conditionals
  my $config = Build::read_config('noarch', []);
  $config->{'warnings'} = 1;
  my $descr = Build::parse($config, $fn);
  # for now, we assume that $fn is a spec file (we could generalize
  # this...)
  $descr->{'sources'} = [map {$descr->{$_}} grep {/^source/} keys(%$descr)];
  $descr->{'patches'} = [map {$descr->{$_}} grep {/^patch/} keys(%$descr)];
  $descr->{'icons'} = [map {@{$descr->{$_}}} grep {/^icon/} keys(%$descr)];
  return $descr;
}

sub write_sources {
  my ($descr, $sfn) = @_;
  open(F, '>>', $sfn) || die("open: $!\n");
  print F "@{$descr->{'sources'}} " if @{$descr->{'sources'}};
  print F "@{$descr->{'patches'}} " if @{$descr->{'patches'}};
  print F "@{$descr->{'icons'}}" if @{$descr->{'icons'}};
  close(F) || die("close: $!\n");
}

my ($dfn, $sfn) = @ARGV;
die("usage: $0 descr sources\n") unless $dfn && $sfn;
my $descr = parse($dfn);
write_sources($descr, $sfn);
