#
#                             IPSTB Project
#                   ---------------------------------
#
# Copyright (C) 2007 NXP Semiconductors B.V.,
# All Rights Reserved.
#
# Filename: record_package_source.pl
#
# This perl script is used to help patch a buildroot tree by
# parsing buildroot package makefiles, extracting the targets
# that are dependent on source tarballs.
# It then prints out make rules that will ensure that when these
# buildroot packages are built, special files are created
# called ".package_source.<SOURCENAME>" with the full path to a
# package source (tarball) file.
#
# For example:-
# package ncurses.mk file contains these particular lines:
#   $(NCURSES_DIR)/.dist: $(DL_DIR)/$(NCURSES_SOURCE)
#   ...
#   ncurses-source: $(DL_DIR)/$(NCURSES_SOURCE)
#
# Therefore this perl script will print out:
#   $(NCURSES_DIR)/.dist: $(TOPDIR)/.package_source.NCURSES
#   ncurses-source: $(TOPDIR)/.package_source.NCURSES
#
# Usage:-
# - cd $(buildroot_BUILDDIR)
# - perl record_package_source.pl */*/*.mk >record_package_source.mk
# - Add a line that includes record_package_source.mk to the buildroot toplevel Makefile.
#
# Rev Date       Author      Comments
#-------------------------------------------------------------------------------
#   1 20070302   batelaan    Initial
#   2 20070302   batelaan    Skip makefile comment lines.

$debug = 0;

print <<'EOT';
$(TOPDIR)/.package_source.%:
	echo $(DL_DIR)/$($*_SOURCE) >$@
EOT

my $fileRX = '(?:[^/]+)';

foreach $f (@ARGV) {
  my ($category, $dir, $name) = $f =~ m!.*($fileRX)/($fileRX)/($fileRX)\.mk$!;
  unless ($name) {
    print STDERR "**WARNING: $f not in format <sub-directory>/<package>/<package>.mk\n";
    next;
  }

  open F, $f || die "$f: $!\n";
  while (defined ($line = <F>)) {
    chomp $line;
    # read continutation lines if any:
    while ($line =~ s/\\$/ /) {
      $line .= <F>;
    }

    # Skip makefile command, comment, and assignment lines:
    next if $line =~ /^\t/;
    next if $line =~ /^\s*#/;
    next if $line =~ /=/;
    # Dependency line?
    if (($targets, $dependencies) = $line =~ m/^(.*?):(.+)/) {
      print STDERR "Dependency line (targets=$targets) (dependencies=$dependencies):\n  $line\n" if $debug;
      foreach $sourceName ($dependencies =~ m{\$\(DL_DIR\)/\$\((\w+)_SOURCE\)}g) {
	print STDERR "Targets depend on source $sourceName\n" if $debug;
	if ($seen{"$targets __ $sourceName"}++) {
	  last;
	}
	print "$targets: \$(TOPDIR)/.package_source.$sourceName\n";
      }
    }
  }
  close F;
}

