#!/usr/bin/perl -w

use warnings;
use strict;
use Fcntl qw(:mode);

(my $scriptname = $0) =~ s/.*\///;

sub write_valamakefile {
    my $automakefile = shift;
    my $valamakefile = $automakefile;

    $valamakefile =~ s/\.am$/.vm/g;

    open AUTOMAKEFILE, "<${automakefile}" or die $!;
    open VALAMAKEFILE, ">${valamakefile}.$$" or die $!;

    my $pattern = '';
    my $built_sources_list = '';
    my $built_sources_assign = '=';
    my $include_seen = 0;

    print VALAMAKEFILE "# Generated by ${scriptname} - DO NOT EDIT\n\n";

    while (my $line = <AUTOMAKEFILE>) {
        $pattern .= $line;
        next if $line =~ /\\$/;

        if ($pattern !~ /^EXTRA_/ && $pattern =~ /^(\w+)_SOURCES/) {
            my ($target, $stamp) = ($1, "$1.valastamp");
            my ($built_sources, $vala_sources) = ($stamp, '');

            while ($pattern =~ s/\b(\S+)\.vala//) {
                $built_sources .= " $1.c $1.h";
                $vala_sources .= " $1.vala";
            }

            $vala_sources =~ s/^\s+//;

            if ($vala_sources) {
                print VALAMAKEFILE << "END-OF-FRAGMENT";
${target}_SOURCES += ${built_sources}

${stamp}: ${vala_sources}
\t\$(VALAC) \$(VALAFLAGS) \$(${target}_VALAFLAGS) \$^
\ttouch ${stamp}

clean-local: vala-clean-${target}

vala-clean-${target}:
\trm -f ${built_sources}

END-OF-FRAGMENT

                $built_sources_list .= " ${built_sources}";
            }
        } elsif ($pattern =~ /^BUILT_SOURCES\s*=/) {
            $built_sources_assign = '+=';
        } elsif ($pattern =~ /^include\s+Makefile.vm/) {
            $include_seen = 1;
        }

        $pattern = '';
    }

    print VALAMAKEFILE << "END-OF-FRAGMENT";
BUILT_SOURCES ${built_sources_assign}${built_sources_list}

Makefile.vm: Makefile.am
\t\$(top_srcdir)/vala-support Makefile.am
END-OF-FRAGMENT

    close VALAMAKEFILE;
    close AUTOMAKEFILE;

    if ($include_seen) {
        print "${scriptname}: creating ${valamakefile}\n";
        rename "${valamakefile}.$$", ${valamakefile};
    } else {
        unlink "${valamakefile}.$$";
    }
}

my @automakefiles = @ARGV;

@automakefiles = `find -name Makefile.am` if not @automakefiles;

for my $automakefile(@automakefiles) {
    $automakefile =~ s/\.\/(.*)\n/$1/;
    write_valamakefile $automakefile;
}

# vim: sw=4 sta et
