#!/usr/bin/perl
# extractsources: pull out lists of _SOURCES from Makefile.am into files

#   Copyright (C) 2005 by ott
#   Part of the Battle for Wesnoth Project http://wesnoth.org/
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License.
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY.
#
#   See the COPYING file for more details.

# This script takes as input a Makefile.am containing _SOURCES variable
# assignments.  It extracts the lists of files in each such assignment
# and creates a file for each list.
# Conditional semantics of the Makefile.am are not dealt with, so the last
# occurrence of each _SOURCES variable will be used, whether inside a
# conditional or not.

use strict;
use File::Basename;

my $DEBUG = 0;
my $filename;

sub process_arg {
    my $path = shift;
    my $out = shift;
    my $arg = shift;
    my $outfile = $path . $out;
    $DEBUG and print STDERR "argument :$arg:\n";
    $DEBUG and print STDERR "opening $outfile for writing\n";
    if (! open(OUTFILE, ">$outfile")) {
        warn "Can't open $outfile for writing, skipping";
	return;
    }
    $arg =~ s/\\\n/\n/g;
    $arg =~ s/\s+/\n/g;
    $arg =~ s/\n+/\n/g;
    $arg =~ s/^\n+//s;
    $DEBUG and print STDERR "argument now :$arg:\n";
    print OUTFILE $arg;
    close OUTFILE;
}

Argument:
while ($filename = shift) {
    $DEBUG and print STDERR "opening $filename for reading\n";
    if (! open(CURRENT, $filename)) {
        warn("cannot open file $filename, skipping");
        next Argument;
    }
    my ($base,$path,$type) = fileparse($filename, qr{\.am});
    if ($type ne '.am') {
	warn "Can only process files ending with .am, skipping $filename";
	next Argument;
    }

    my $out;
    my $state = 0;
    my $arg = '';
    while (<CURRENT>) {                                                         
	if ($state == 0) {
	    if ( /^(\w+)_SOURCES\s*=\s*(.*)/s ) {
		$out = "$1_sources";
		$arg = $2;
		# chomp $arg;
		if ( $arg =~ /\\$/ ) {
		    $state = 1;
		} else {
		    process_arg( $path, $out, $arg );
		}
	    } # else keep looking
	} elsif ($state == 1) { # looking for more lines
	    $arg .= $_;
	    if ( ! /\\$/ ) { # got the whole SOURCES line, substitute
		process_arg( $path, $out, $arg );
		$arg = '';
		$out = '';
		$state = 0;
	    }
	} else {
	    die 'Internal error, quitting';
	}
    }
    process_arg( $path, $out, $arg ) if $arg;
}
